Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a filled triangle in android canvas?

So I'm drawing this triangle in android maps using the code below in my draw method:

paint.setARGB(255, 153, 29, 29); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true);  Path path = new Path(); path.moveTo(point1_returned.x, point1_returned.y); path.lineTo(point2_returned.x, point2_returned.y); path.moveTo(point2_returned.x, point2_returned.y); path.lineTo(point3_returned.x, point3_returned.y); path.moveTo(point3_returned.x, point3_returned.y); path.lineTo(point1_returned.x, point1_returned.y); path.close();  canvas.drawPath(path, paint); 

The pointX_returned are the coordinates which I'm getting from the fields. They are basically latitudes and longitudes. The result is a nice triangle but the insider is empty and therefore I can see the map. Is there a way to fill it up somehow?

like image 815
Pavel Avatar asked Aug 17 '10 09:08

Pavel


People also ask

How to draw triangle in Canvas android studio?

Simply call drawTriangle with the Canvas to draw on, the Paint to draw with, the X/Y coordinates to draw at, and the width of the triangle. Not bad, with a little customization such as modifying the color or applying antialiasing this can work quite well for your triangle drawing needs.


2 Answers

Ok I've done it. I'm sharing this code in case someone else will need it:

super.draw(canvas, mapView, true);  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  paint.setStrokeWidth(2); paint.setColor(android.graphics.Color.RED);      paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true);  Point point1_draw = new Point();         Point point2_draw = new Point();     Point point3_draw = new Point();  mapView.getProjection().toPixels(point1, point1_draw); mapView.getProjection().toPixels(point2, point2_draw); mapView.getProjection().toPixels(point3, point3_draw);  Path path = new Path(); path.setFillType(Path.FillType.EVEN_ODD); path.moveTo(point1_draw.x,point1_draw.y); path.lineTo(point2_draw.x,point2_draw.y); path.lineTo(point3_draw.x,point3_draw.y); path.lineTo(point1_draw.x,point1_draw.y); path.close();  canvas.drawPath(path, paint);  //canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);  return true; 

Thanks for the hint Nicolas!

like image 93
Pavel Avatar answered Oct 21 '22 13:10

Pavel


You probably need to do something like :

Paint red = new Paint();  red.setColor(android.graphics.Color.RED); red.setStyle(Paint.Style.FILL); 

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

like image 44
Nicolas C. Avatar answered Oct 21 '22 14:10

Nicolas C.