Application freezes when scaling a raster image in canvas

Drawing text on Bitmap

public Bitmap textAsBitmap(String text, float textSize, int textColor) {
    m_paint.setTextSize(textSize);
    m_paint.setColor(textColor);
    m_paint.setTextAlign(Paint.Align.LEFT);
    int width = (int) ( m_paint.measureText(text) + 0.5f);  // round
    float baseline = (int) (- m_paint.ascent() + 0.5f); // ascent() is negative
    int height = (int) (baseline +  m_paint.descent() + 0.5f);         
    final  Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
    canvas1.setBitmap(image);
    canvas1.drawText(text, 0, baseline, m_paint);        
    return image;
}

Step 2. Drawing a canvas

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();

    if (CustomTextview.GetDB().size() != 0) {
        for (CustomTextview textview : CustomTextview.GetDB()) {
            scale = textview.GETSCALE();
          final  Bitmap bitmap= textAsBitmap(textview.text,textview.size*scale,textview.color);
            if (bitmap!=null)
            canvas.drawBitmap(bitmap, textview.X, textview.Y, textview.paint);
      }       
    }
    canvas.restore();

}

I use a scale receiver to scale bitmap.but, when it ever scales, it freezes in 5-10 minutes.

+4
source share
3 answers

You can simply draw text on the canvas directly without first creating a bitmap.

To do this, create a Paint with the correct configuration, calculate how large your text will be when it is drawn, and then draw the text directly on the canvas.

Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setAntiAlias(true);
textPaint.setFakeBoldText(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(30f);


String myText = "This is a test";
Rect textBounds = new Rect();
textPaint.getTextBounds(myText, 0, myText.length(), bounds);

canvas.drawText(myText, 0, myText.length() rect.width()/2, rect.height()/2, textPaint);

In the above code, the text will be highlighted in the center, but you can easily change it to suit your needs.

+1

.

android:largeHeap="true"

AndroidMenifest.xml.

<application
           android:largeHeap="true" >
</application>

, .

0

The reason it hangs is probably because creating a large number of bitmaps in this way will quickly lead to a lack of memory. If you really need a bitmap, you can create one bitmap and reuse it. Better, probably, as another suggested solution, use canvas api directly. You can even use a single instance of Paint to avoid memory overhead.

0
source

Source: https://habr.com/ru/post/1569863/


All Articles