我创建了一个扩展SurfaceView的类,以便循环一系列ARGB位图。
除了为每个新帧保留(通常但并非总是)基础位图的状态外,这通常可以工作。
换句话说,如果我显示的第一帧是不透明的,而随后的帧是透明的,则在绘制新帧时,不会清除原始帧中的不透明像素。
此行为使我感到困惑,因为SurfaceHolder.lockCanvas()的文档专门指出:
“因此,Surface的内容永远不会保留在unlockCanvas()和lockCanvas()之间,因此,必须写入Surface区域内的每个像素。”
如果我只有纯色背景,则调用canvas.drawARGB(255,0,0,0)可以成功将其清除为黑色...但是我想使用透明背景,但无法将其清除为透明背景颜色,因为canvas.drawARGB(0,0,0,0)无效。
import java.util.ArrayList;
import java.util.Random;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/*
* Accepts a sequence of Bitmap buffers and cycles through them.
*/
class AnimatedBufferView extends SurfaceView implements Runnable
{
Thread thread = null;
SurfaceHolder surfaceHolder;
volatile boolean running = false;
ArrayList<Bitmap> frames;
int curIndex = 0;
public AnimatedBufferView(ArrayList<Bitmap> _frames, Context context)
{
super(context);
surfaceHolder = getHolder();
frames = _frames;
}
public void onResume(){
running = true;
thread = new Thread(this);
thread.start();
}
public void onPause(){
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run()
{
// TODO Auto-generated method stub
while(running)
{
if(surfaceHolder.getSurface().isValid())
{
Canvas canvas = surfaceHolder.lockCanvas();
//clear the buffer?
//canvas.drawARGB(255, 0, 0, 0);
//display the saved frame-buffer..
Matrix identity = new Matrix();
Bitmap frame = frames.get(curIndex);
canvas.drawBitmap(frame, identity, null);
surfaceHolder.unlockCanvasAndPost(canvas);
curIndex = (curIndex + 1) % frames.size();
try {
thread.sleep( 100 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
最佳答案
好的,发现问题是默认的Porter-Duff绘制模式使绘制透明颜色成为不可能。只需更改模式即可。即
Canvas canvas surfaceView.lockCanvas();
canvas.drawColor(0, Mode.CLEAR);
关于android - SurfaceView.lockCanvas()无法正确清除位图缓冲区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11910675/