How to draw a triangle, a star, a square or a heart on the canvas?

nickfrancis.me picture nickfrancis.me · Aug 10, 2011 · Viewed 34.5k times · Source

I am able to draw a circle and a rectangle on canvas by using
path.addCircle()

and

path.addRect().

And now I am wondering how to draw a triangle or a star or a square or a heart?

Answer

roomtek picture roomtek · Feb 3, 2013

For future direct answer seekers, I have drawn an almost symmetric star using canvas, as shown in the image:

Star Image

The main tool is using Paths.

Assuming you have setup:

Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);

Path path = new Path();

Then in you onDraw you can use the path like I do below. It will scale properly to any sizes canvas

@Override
protected void onDraw(Canvas canvas) {

    float mid = getWidth() / 2;
    float min = Math.min(getWidth(), getHeight());
    float fat = min / 17;
    float half = min / 2;
    float rad = half - fat;
    mid = mid - half;

    paint.setStrokeWidth(fat);
    paint.setStyle(Paint.Style.STROKE);

    canvas.drawCircle(mid + half, half, rad, paint);

    path.reset();

    paint.setStyle(Paint.Style.FILL);


        // top left
        path.moveTo(mid + half * 0.5f, half * 0.84f);
        // top right
        path.lineTo(mid + half * 1.5f, half * 0.84f);
        // bottom left
        path.lineTo(mid + half * 0.68f, half * 1.45f);
        // top tip
        path.lineTo(mid + half * 1.0f, half * 0.5f);
        // bottom right
        path.lineTo(mid + half * 1.32f, half * 1.45f);
        // top left
        path.lineTo(mid + half * 0.5f, half * 0.84f);

        path.close();
        canvas.drawPath(path, paint);

    super.onDraw(canvas);

}