优化自定义裁剪绘图

时间:2013-10-09 05:41:47

标签: android performance android-layout memory

我已经按照以下方式实现了组件的绘图:

@Override
protected void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();

    if (mFinalBitmap == null) {
        mFinalBitmap = Bitmap.createBitmap(w, h,
                Bitmap.Config.ARGB_8888);
    }

    if (mTempCanvas == null) {
        mTempCanvas = new Canvas(mFinalBitmap);
    }

    if (mBackgroundBitmap == null) {
        mBackgroundBitmap = createBitmap(R.drawable.rounded_background,
                w, h);
    }

    if (mBackgroundImage == null) {
        mBackgroundImage = createBitmap(R.drawable.image_for_background, w, h);
    }

    mTempCanvas.drawBitmap(mBackgroundBitmap, 0, 0, null);
    mTempCanvas.drawBitmap(mBackgroundImage, 0, 0, mPaint);

    canvas.drawBitmap(mFinalBitmap, 0, 0, null);
}

private Bitmap createBitmap(int id, int width, int height) {

    Bitmap bitmap = BitmapFactory.decodeResource(getContext()
            .getResources(), id);

    return Bitmap.createScaledBitmap(bitmap, width, height, false);
}

mPaint的地方

mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

enter image description here

我想知道代码是好的,还是可以针对相同的结果进行优化,它使用大量内存并且是OutOfMemoryError的潜在触发器。

感谢。

1 个答案:

答案 0 :(得分:1)

使用BitmapShader可以使用要绘制的图像实现以下绘制,然后我只需要使用着色器创建ALPHA_8 Bitmap以使用Paint对象进行绘制。但是着色器固定在窗口坐标中,因此在滚动组件中使用此方法可能会导致一些问题,因为Matrix需要正确转换。

// Create bitmap shader
if (mShaderBitmap == null) {
    mShaderBitmap = use wanted bitmap here.
    BitmapShader shader = new BitmapShader(mShaderBitmap,
            TileMode.CLAMP, TileMode.CLAMP);
    mPaint.setShader(shader);
}

// Create alpha bitmap to draw with shader paint
if (mBitmapToDraw == null) {
    mBitmapToDraw = load the shape here with ALPHA_8 Config
}

canvas.drawBitmap(mBitmapToDraw, 0, 0, mPaint);