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 text 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
clipRectonly restricts drawing to the givenrect, so that any draw calls outside thatrectwill be clipped to thatrect. Thus, my understanding ofclipRectwas wrong.This means that, in order to use
StaticLayoutI’d have to first draw it to aBitmapthat is the size of myrectand then draw thatBitmapto myCanvasat the coordinates I need.However, I have resorted to using
Canvas.drawTextandTextPaint.breakTextinstead (so I don’t have to create aBitmapeverytime).