简体   繁体   中英

Canvas partial text drawing

I need to draw text on 2 consecutive bitmaps that form a single continues bitmap.

  • The text can begin on the first bitmap and end on the second bitmap.
  • A letter can begin on the first bitmap but end on the second bitmap.

在此处输入图片说明

I can draw the text in full twice using a negative offset on the second bitmap

//first bitmap
canvas1.drawText(text, position, top, paint);

//second bitmap
canvas2.drawText(text, -lengthOfTextOnFirstBitmap, top, paint);

Seems like the wrong way to address the issue, I would like to support n bitmaps and I'm looking for a better solution.

Any thoughts?

Just translate the canvas so that you draw in the same "place", but the canvas is positioned just to the right of the first canvas. This should make a pixel-perfect text rendering.

//first bitmap
canvas1.drawText(text, position, top, paint);

//second bitmap
canvas2.translate(width_of_1st_bitmap, 0);
canvas2.drawText(text, position, top, paint);
canvas2.translate(-width_of_1st_bitmap, 0);

The answer is No. You can't use drawText to partially draw in one Bitmap and then in another bitmap. drawText is a single atomic method call that can be performed on a single instance of Canvas . And you can't switch bitmaps of the canvas in the middle of a drawText call.

But there are alternatives. If you are going to have Bitmap1 and Bitmap2 in the memory at the same time, and you are not looking for any layering effects (xFermode drawing) then you could just simply use a single Bitmap and then get two bitmaps out of them.

But if you are going to draw in 2 bitmaps to avoid OutOfMemory error, then you can do something as below.

  1. There is no need for 2 canvas objects. Just have one canvas and use setBitmap() to switch bitmaps.
  2. Any draw operation in Canvas is atomic. So instead of using a single drawText(text) you will need to split the text into two and then draw one in the first bitmap and the other in the second. You can use Paint.getTextBounds() or Paint.measureText() to know how to split the text . But this is really messy and you need to calculate a lot of stuff.
  3. drawText is a very fast call. It won't take much time even if you call it with a large text for 10 times. So I don't really think you need all this optimizations at all. However if you going to use 'drawText' and then 'drawCircle' and then 'drawRect' (multiple draw calls), then you can record these calls in Picture . And then you can playback this Picture on the Canvas by switching the bitmaps. This will reduce the method overhead time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM