njsokalski avatar image
0 Votes"
njsokalski asked njsokalski commented

Cropping a Canvas Before Returning From OnDraw

I have a custom View in which I override the OnDraw method. Before returning the Canvas, I want to crop it, but I cannot find a way to do this. SetViewport does not work, and none of the .Clip* methods seem to do anything. How can I control what part of the Canvas is actually used?

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Do you mean that how to clip Canvas in Android?

If so, after Android API 26, Google has been released Clip methods for Canvas, you can refer to this documentation Canvas Public methods to get more details.

You could also use the following code to crop:

protected override void OnDraw(Canvas canvas)
    var bitmap = Bitmap.CreateBitmap(bitmapImage.Width, bitmapImage.Height, Bitmap.Config.Argb8888);
    var paint = new Paint(PaintFlags.AntiAlias);
    canvas.DrawCircle(100.0f, 100.0f, 50.0f, paint);
    paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcOut));
    canvas.DrawBitmap(bitmap, 0, 0, paint);
0 Votes 0 ·
njsokalski avatar image njsokalski YonglunLiu-MSFT ·

As I said in my original post, the .Clip* methods seem to be getting ignored. For example, the following lines have no effect on my result:

 canvas.ClipPath(AndroidX.Core.Graphics.PathParser.CreatePathFromPathData("M0 0H220V220H0Z"));
 canvas.ClipOutRect(0, 0, 400, 400);

Is there something wrong with this code? I'm not sure I understand your code, what is the Bitmap you are creating? Where does your bitmapImage variable come from? Are there any tutorials on clipping and/or cropping? I looked at

But that seems like it is more for bitmaps as well. What should I do?

0 Votes 0 ·

Are you using HC or above or otherwise using hardware acceleration?

If so, the method ClipPath is unsupported and problematic.

You can refer to Hardware acceleration to get more details.

In addition, ClipRect means:

Intersect the current clip with the specified rectangle, which is expressed in local coordinates.

For this reason, you need to use to save modifications to the matrix/clip state.

0 Votes 0 ·

May I know if you have got any chance to check my answer? I am glad to help if you have any other questions.

0 Votes 0 ·
Show more comments

0 Answers