应用程序在画布中缩放位图时挂起

时间:2015-01-04 10:12:29

标签: android canvas bitmap draw

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;
}

第2步 - 绘制画布

@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();

}

我正在使用缩放监听器来缩放位图。但是当缩放时,它会在5到10分钟后挂起。

3 个答案:

答案 0 :(得分:1)

您可以直接在Canvas上绘制文本,而无需先创建位图。

为此,使用正确的配置创建一个Paint,计算绘制文本时的大小,然后将文本本身直接绘制到画布上。

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);

上面的代码会将文本绘制为中心,但您可以轻松更改此内容以满足您自己的需求。

答案 1 :(得分:0)

你可以试试这个。

android:largeHeap="true"

AndroidManifest.xml中的应用程序内部。比如

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

希望能正常运作。感谢

答案 2 :(得分:0)

它挂起的原因可能是因为以这种方式创建大量位图会很快导致内存不足。 如果您确实需要位图,则可以创建单个位图并重新使用它。更好的可能是直接使用canvas api的其他建议解决方案。您甚至可以使用一个Paint实例来避免内存开销。