Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDraw triangle on Button

In a class I created that extends Button, I overrode the onDraw function to create a triangle in the right side of the button pointing to the center:
Desired result

Instead, this is what I get:
Actual result

This is 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);
}
like image 359
Colum Srečko Avatar asked Apr 25 '26 14:04

Colum Srečko


1 Answers

You forgot to move to its initial point.

Something like

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

before your first lineTo()

Because lineTo() needs a "last point" to start the 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:

    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);
like image 140
Phantômaxx Avatar answered Apr 28 '26 05:04

Phantômaxx