Draw a circle partially filled dynamically

2019-05-28 12:21发布

问题:

I'm trying to play with canvas. I could draw some triangles and fill it partially drawing a path and paint it.I used Path, Points and Line. It was a great exercise to remember trigonometry. For now I would like to do the same with a circle, as you can see below. I want set a percentage and to fill this circle until the circle's height * percentage. How could me draw a circle like that with canvas or some lib?

回答1:

You should think about it a little differently. The way I'd do it is to draw a coloured rectangle (where the height is a percentage of the circle's intended height) and then crop it with a circle. This answer explains how to crop an image in a circular shape (I'd rather link than retype the code here).



回答2:

I finally got do it. I created two methods. As roarster suggested, I created a white rectangle as mask where the height is a percentage of the circle's intended height.

private Bitmap drawWithPorterDuff(Bitmap original, Bitmap mask, PorterDuff.Mode mode) {
    Bitmap bitmap = Bitmap.createBitmap(original.getWidth(), original.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Paint maskPaint = new Paint();
    maskPaint.setAntiAlias(true);
    canvas.drawBitmap(original, 0, 0, null);
    maskPaint.setXfermode(new PorterDuffXfermode(mode));
    canvas.drawBitmap(mask, 0, 0, maskPaint);
    Bitmap edge = BitmapFactory.decodeResource(getResources(), R.drawable.edge);
    maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
    canvas.drawBitmap(edge, 0, 0, maskPaint);
    return bitmap;
}

public Bitmap createMask(int width, int height) {
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);
    paint.setAntiAlias(true);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawRect(0, 0, width, height, paint);
    return bitmap;
}

At view's constructor I created a init() method with the folling code

    PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
    Bitmap original = BitmapFactory.decodeResource(getResources(), R.drawable.blue_graph);
    Bitmap mask = createMask(original.getWidth(), (int) ((original.getHeight()) * (1 - percentage)));
    Bitmap result = drawWithPorterDuff(original, mask, mode);
    imageView.setImageBitmap(result);