通过缓存矩阵优化Android画布背景绘图
我有一张SurfaceView画布,我正在画一个场景。 画布经过变换以适应逻辑场景大小1024x768(而实际屏幕为800x480),并支持其上的缩放/滚动导航。 因为我不希望在侧面有黑色条纹(适合4:3到16:9),所以我使用了一个不同的背景位图,它有“拉伸”的侧面来覆盖比率差异。 情节的另一个转折点是,我需要同时支持手机和桌子。对于平板电脑,我正在加载更高质量(大小)的图像;对于手机,我正在从磁盘加载背景位图时缩小背景位图。 下面是我想要的代码(虽然可能不是最好的方式),特别是,我感觉背景计算可以缓存到矩阵中,稍后在通过缓存矩阵优化Android画布背景绘图,android,optimization,matrix,bitmap,android-canvas,Android,Optimization,Matrix,Bitmap,Android Canvas,我有一张SurfaceView画布,我正在画一个场景。 画布经过变换以适应逻辑场景大小1024x768(而实际屏幕为800x480),并支持其上的缩放/滚动导航。 因为我不希望在侧面有黑色条纹(适合4:3到16:9),所以我使用了一个不同的背景位图,它有“拉伸”的侧面来覆盖比率差异。 情节的另一个转折点是,我需要同时支持手机和桌子。对于平板电脑,我正在加载更高质量(大小)的图像;对于手机,我正在从磁盘加载背景位图时缩小背景位图。 下面是我想要的代码(虽然可能不是最好的方式),特别是,我感觉背景计
canvas.drawBitmap(位图、矩阵、绘画)中使用代码>
(此外,我无法通过使用这些偏移量转换画布来获得drawBitmap(位图、左、上、绘制)的等效位置,我也很好奇为什么)
这是绘图例程:
public void draw(Canvas canvas) {
canvas.save();
float midX = width/2;
float midY = height/2;
// zoom out to fit logical view, and translate for future
// sprite drawing with logical coordinates
// x,y and zoom are calculated in on init and updated in touch events
canvas.translate(x, y);
canvas.scale(zoom, zoom, midX, midY);
// background part
if(back != null && !back.isRecycled()) {
// todo: these can probably be pre-calculated for optimization
// todo: but so far I couldn't get it right..
if(bgMatrix != null) { // this is where I'm thinking of using the cached matrix
canvas.drawBitmap(back, bgMatrix, paint);
}
else {
float offsetW = (width-back.getWidth())/2;
float offsetH = (height-back.getHeight())/2;
canvas.save();
// bgScaleFactor is calculated upon setting the bg bitmap
// it says by how much we need to scale the image to fill the canvas
// taking into account the image (possible) downscale
canvas.scale(bgScaleFactor, bgScaleFactor, midX, midY);
// this doesn't work: canvas.postTranslate(offsetW, offsetH) and use 0,0 for next draw
canvas.drawBitmap(back, offsetW, offsetH, paint);
// todo: here I would like to save a matrix which represents
// how the back bitmap was drawn onto the canvas
// so that next time these calculations can be avoided
// this fails: bgMatrix = canvas.getMatrix();
canvas.restore();
}
// draw scene shapes on transformed canvas
if(shapes != null){
shapes.onDraw(canvas);
}
canvas.restore();
}