如何在Android Canvas上绘制实心三angular形

我有扩展View类的类MyView。 MyView应绘制实心三angular形。 我画了一个三angular形,但我无法填充它。 这是我的onDraw()方法:

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(android.graphics.Color.BLACK); canvas.drawPaint(paint); paint.setStrokeWidth(4); paint.setColor(android.graphics.Color.RED); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true); Point a = new Point(0, 0); Point b = new Point(0, 100); Point c = new Point(87, 50); Path path = new Path(); path.setFillType(FillType.EVEN_ODD); path.moveTo(ax, ay); path.lineTo(bx, by); path.moveTo(bx, by); path.lineTo(cx, cy); path.moveTo(cx, cy); path.lineTo(ax, ay); path.close(); canvas.drawPath(path, paint); } 

这就是我得到的结果:

在这里输入图像说明

Solutions Collecting From Web of "如何在Android Canvas上绘制实心三angular形"

我find了答案

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(android.graphics.Color.BLACK); canvas.drawPaint(paint); paint.setStrokeWidth(4); paint.setColor(android.graphics.Color.RED); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true); Point a = new Point(0, 0); Point b = new Point(0, 100); Point c = new Point(87, 50); Path path = new Path(); path.setFillType(FillType.EVEN_ODD); path.lineTo(bx, by); path.lineTo(cx, cy); path.lineTo(ax, ay); path.close(); canvas.drawPath(path, paint); } 

我想指出的是,你不应该从onDraw()中初始化一个对象,因为它被多次调用并导致性能问题。

这个答案在@Egis的答案中给出的数字来自哪里,提供了一些清晰的说明。 (这将画一个倒三angular形,写在kotlin)

 class TriangleView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { val paint = Paint() val path = Path() override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas ?: return canvas.drawPath(configurePath(canvas.width.toFloat(), path), configurePaint(paint)) } fun getHeight(width: Double): Float { return Math.sqrt((Math.pow(width, 2.0) - Math.pow((width / 2), 2.0))).toFloat() } fun configurePaint(paint: Paint): Paint { paint.color = android.graphics.Color.WHITE paint.isAntiAlias = true return paint } fun configurePath(width: Float, path: Path): Path { path.lineTo((width / 2f), getHeight(width.toDouble())) path.lineTo(width, 0F) path.lineTo(0f, 0f) return path } } 

获得高度函数是毕达哥拉斯定理,并且将始终find等边三angular形的高度约为其边长的87%

Gist可以在这里find,它包含另一个方向的代码