我想了解如何在自定义的 View
中正确使用硬件加速(如果可用)来持久地进行动画。这是我的 onDraw()
的基本原则:
canvas.drawColor(mBackgroundColor);
for (Layer layer : mLayers) {
canvas.save();
canvas.translate(layer.x, layer.y);
//Draw that number of images in a grid, offset by -1
for (int i = -1; i < layer.xCount - 1; i++) {
for (int j = -1; j < layer.yCount - 1; j++) {
canvas.drawBitmap(layer.bitmap, layer.w * i, layer.h * j, null);
}
}
//If the layer's x has moved past its width, reset back to a seamless position
layer.x += ((difference * layer.xSpeed) / 1000f);
float xOverlap = layer.x % layer.w;
if (xOverlap > 0) {
layer.x = xOverlap;
}
//If the layer's y has moved past its height, reset back to a seamless position
layer.y += ((difference * layer.ySpeed) / 1000f);
float yOverlap = layer.y % layer.h;
if (yOverlap > 0) {
layer.y = yOverlap;
}
canvas.restore();
}
//Redraw the view
ViewCompat.postInvalidateOnAnimation(this);
我正在
onAttachedToWindow()
中启用硬件层,并在onDetachedFromWindow()
中禁用它们,但我想知道是否真的在使用它。基本上,调用drawBitmap()
的循环永远不会改变;唯一改变的是Canvas
的平移。 Bitmap
自动保存到GPU作为纹理背后的过程,还是需要手动执行某些操作?
setLayerType(View.LAYER_TYPE_HARDWARE, null);
?GPU仅在用户正在主动滚动时缓存图像,但在其他情况下不会缓存,这是为了消耗更少的资源而做出的权衡。 - Vrashabh Irde