与SurfaceView
您应该创建一个静态ArrayList
或Vector
存储您的Bitmap
和绘制位图onDraw
public class Panle extends SurfaceView implements SurfaceHolder.Callback {
private static ArrayList<Bitmap> mElements;
private CanvasThread canvasThread;
private Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
public Panle(Context context) {
super(context);
mElements = new ArrayList<Bitmap>();
getHolder().addCallback(this);
canvasThread = new CanvasThread(getHolder(), this);
p.setXfermode(new PorterDuffXfermode(Mode.SRC));
p.setColor(Color.TRANSPARENT);
p.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
}
@Override
public void draw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(0xffffffff);
if (mElements != null && mElements.size() != 0) {
for (int i = 0; i <= mElements.size() - 1; i++) {
canvas.drawBitmap(mElements.get(i), 50, 50, p);// For example i fixed position at 50 50. You can change to another position
}
}
super.draw(canvas);
}
public static ArrayList<Bitmap> setmElements() {
return mElements;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!canvasThread.isAlive()) {
canvasThread = new CanvasThread(getHolder(), this);
canvasThread.setRunning(true);
canvasThread.start();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (canvasThread.isAlive()) {
canvasThread.setRunning(false);
}
}
}
现在我们需要在面板类中处理线程。
public class CanvasThread extends Thread {
private SurfaceHolder _surfaceHolder;
private Panle _panel;
private boolean _run = false;
public CanvasThread(SurfaceHolder surfaceHolder, Panle panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
@Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
在 xml 中创建面板并在您的活动中获取它。为了SDcard
使用 Intent 打开 Gallery 来绘制图像,我使用它将检索到的图像放入 onActivityForResult。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == Constants.REQUEST_CODE_GETTING_IMAGE) {
if (data != null) {
Uri dataUri = data.getData();
Bitmap bitmap = null;
bitmap = Utils.decodeSampledBitmapFromFile(ImageUtil.getRealPathFromURI(CheDetailActivity.this, dataUri), Panel.getPanelW(), Panel.getPanelH());// I resize image from Gallery to avoid OOM
if (bitmap != null) {
Panel.getmElements().add(bitmap);
}
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Panel.getElements.add(bitmap);
您可以使用您可以看到的另一个教程是2D 教程系列自由添加任何位图,其中显示了非常基本的步骤。