0

我已经实现了组件的绘图,如下图所示:

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

在此处输入图像描述

我想知道代码是否很好,或者可以针对相同的结果进行优化,它使用大量内存并且是OutOfMemoryError.

谢谢。

4

1 回答 1

1

使用要绘制的图像可以实现以下BitmapShader绘制,然后我只需要创建 ALPHA_8Bitmap即可使用着色器使用对象进行绘制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);
于 2013-12-04T09:53:30.870 回答