问题描述
我在图片下面的方式实现图纸的组件如:
I've implemented drawing for component like in picture following way:
@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有
Where mPaint has
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
我想知道的code是否好,还是可以为相同的结果进行优化,它使用的内存很多的,并且是的OutOfMemoryError
的潜在诱因。
I'm wondering whether the code is good, or can be optimized for same result, it uses lot's of memory and is an potential trigger for OutOfMemoryError
.
感谢。
推荐答案
可以使用可以实现如下图 BitmapShader
与要绘制的图像,那么我只需要创建ALPHA_8 位图
使用着色器油漆
对象进行绘制。然而着色器固定到窗口坐标,因此,使用滚动元件内部这种方法可能会导致一些问题,因为矩阵
需要正确翻译。
Following drawing can be achieved using BitmapShader
with the image to be drawn, then I only need to create ALPHA_8 Bitmap
to draw with Paint
object using the shader. However shaders are pinned into window coordinates, so using this method inside scrolling components can cause some problems because the Matrix
needs to be translated properly.
// 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);
这篇关于优化自定义剪裁绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!