2013-12-12 58 views
16

我有一個擴展視圖類類MyView的。 MyView應繪製實心三角形。我畫了一個三角形,但我無法填充它。這是我的onDraw()方法:如何畫實心三角Android上的帆布

@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(a.x, a.y); 
    path.lineTo(b.x, b.y); 
    path.moveTo(b.x, b.y); 
    path.lineTo(c.x, c.y); 
    path.moveTo(c.x, c.y); 
    path.lineTo(a.x, a.y); 
    path.close(); 

    canvas.drawPath(path, paint); 
} 

這是我得到的結果:

enter image description here

回答

20

我已經找到了答案

@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(b.x, b.y); 
    path.lineTo(c.x, c.y); 
    path.lineTo(a.x, a.y); 
    path.close(); 

    canvas.drawPath(path, paint); 
} 
+4

第一了lineTo應的moveTo。否則,它將從點(0,0)開始繪製。在這種情況下不是問題,但是因爲我想從中心抽籤,所以我面臨這個問題。 – lucasjmatias

0

我想指出的是,你永遠不應該initiialize從的onDraw(),因爲它被調用多次,導致性能問題的對象。

0

這個答案提供了其中由@Egis在答案中給出的數字來自一個有點清晰。 (這將繪製一個倒等邊三角形和寫入科特林)

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 
    } 
} 

的get高度功能是Pythagoras' Theorem和總能找到一個等邊三角形的高度爲〜其邊長的87%

Gist可以在這裏找到,它包含代碼的另一個方向