I created a subclass of SurfaceView to abstract canvas operations, such as drawBitmap (among others), as shown below:
public class MyView extends SurfaceView {
public MyView(Context c) {
super(c);
this.canvasHolder = this.getHolder();
this.canvasHolder.addCallback(surfaceHolderCallback);
}
public void drawBitmap(Bitmap bitmap, float width, float height, Paint p) {
canvas.drawBitmap(bitmap, width, height, p);
}
private SurfaceHolder.Callback surfaceHolderCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
canvas = holder.lockCanvas();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {}
};
public void flush() {
this.canvasHolder.unlockCanvasAndPost(this.canvas);
this.canvas = this.canvasHolder.lockCanvas();
}
The full initialization of SurfaceView depends on the callback, in which I get access to the canvas I need to manipulate. Otherwise, I get a NullpointerException on the first drawBitmap call.
The problem is that I want to allow the use of the class quite directly, as shown below. To do this, I need to abstract all of this initialization mechanism with callback and ensure that the drawBitmap has access to a valid canvas (not null).
Any ideas how to do this?
MyView view = new MyView(getBaseContext());
String source = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/abc.png";
view.drawBitmap(BitmapFactory.decodeFile(source).copy(Bitmap.Config.ARGB_8888, true), 0, 0, null);
view.flush();