开发者

How to properly use clipRect?

I'm writing a custom View, but I can't really figure out how to use clipRect on a Canvas. I need this because I'm calling draw(Canvas) on another object and I'd like to give it my own (clipped) Canvas. My current solution is:

StaticLayout sl = new StaticLayout(text, tp, (int) (rect.right - rect.left), Alignment.ALIGN_NORMAL, 1f, 0f, true);

Bitmap layoutBitmap = Bitmap.createBitmap((int) (rect.right - rect.left), (int) (rect.bottom - rect.top), Config.ARGB_8888);
Canvas layoutCanvas = new Canvas(layoutBitmap);
sl.draw(layoutCanvas);

canvas.drawBitmap(layoutBitmap, null, rect, null);

However, this feels dirty, creating a new bitmap and a new canvas every time (I'm using this method to draw tex开发者_如何学Pythont in a box, see my previous question).

What I'd like to do is something like this:

StaticLayout sl = new StaticLayout(text, tp, (int) (rect.right - rect.left), Alignment.ALIGN_NORMAL, 1f, 0f, true);

canvas.save();
canvas.clipRect(rect, Region.Op.REPLACE);
sl.draw(canvas);
canvas.restore();

That "feels" much better, except that it doesn't work. Am I using clipRect wrong? Do I not understand what it's actually for or how to use it? Please advise.

P.S. My understanding of clipRect is that after that clipRect call, 0, 0 should actually translate to rect.left, rect.top.


After a bit of experimenting, it seems that clipRect only restricts drawing to the given rect, so that any draw calls outside that rect will be clipped to that rect. Thus, my understanding of clipRect was wrong.

This means that, in order to use StaticLayout I'd have to first draw it to a Bitmap that is the size of my rect and then draw that Bitmap to my Canvas at the coordinates I need.

However, I have resorted to using Canvas.drawText and TextPaint.breakText instead (so I don't have to create a Bitmap everytime).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜