OnDraw triangle on a button

In a class I created that extends Button

, I redefined the function onDraw

to create a triangle on the right side of the button pointing to the center:
Desired result

Instead, I get:
Actual result

Here's what I wrote:

Paint paint = new Paint();

@Override
public void onDraw(Canvas canvas)
{
    Paint paint = new Paint();

    paint.setColor(android.graphics.Color.BLACK);
    canvas.drawPaint(paint);

    paint.setStrokeWidth(4);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    paint.setAntiAlias(true);

    Point center = new Point(getWidth()/2, getHeight()/2);    
    Point a=new Point(getWidth(), 0);;
    Point b=new Point(getWidth(), getHeight());;

    paint.setColor(Color.RED);    

    Path path= new Path();
    path.setFillType(Path.FillType.EVEN_ODD);
    path.lineTo(b.x, b.y);
    path.lineTo(center.x, center.y);
    path.lineTo(a.x, a.y);
    path.close();
    canvas.drawPath(path, paint);
}

      

+3


source to share


1 answer


You forgot to move to the starting point.

Something like

path.moveTo(point1_draw.x,point1_draw.y);

      

before the first lineTo()



Because it lineTo()

takes a "last point" to start a segment.

void lineTo(float x, float y) // Add a line from the last point to the specified point (x,y).

      

So in the end, your cod will look like this:

    Path path= new Path();
    path.setFillType(Path.FillType.EVEN_ODD);
    path.moveTo(a.x, a.y);           // Move to a
    path.lineTo(center.x, center.y); // Segment from a to center
    path.lineTo(b.x, b.y);           // Segment from center to b
    path.close();                    // Segment from b to a
    canvas.drawPath(path, paint);

      

+2


source







All Articles