Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active December 31, 2015 00:09
Show Gist options
  • Save niusounds/7905659 to your computer and use it in GitHub Desktop.
Save niusounds/7905659 to your computer and use it in GitHub Desktop.
レイヤーごとのBitmapを保持して重ねて描画するViewのサンプル
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;
public class LayerImageView extends View {
private List<Layer> layers = new ArrayList<Layer>();
private Canvas tmpCanvas = new Canvas();
public LayerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public LayerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LayerImageView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Layer l : layers) {
tmpCanvas.setBitmap(l.bitmap);
tmpCanvas.save();
l.onLayerDrawingListener.draw(tmpCanvas);
tmpCanvas.restore();
canvas.drawBitmap(l.bitmap, 0, 0, l.paint);
}
}
public Layer createLayer() {
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
Layer layer = new Layer(bitmap);
return layer;
}
public void addLayer(Layer layer) {
layers.add(layer);
}
public void addLayer(int index, Layer layer) {
layers.add(index, layer);
}
public void setLayer(int index, Layer layer) {
layers.set(index, layer);
}
public boolean removeLayer(Layer layer) {
return layers.remove(layer);
}
public List<Layer> getLayers() {
return layers;
}
public static class Layer {
private final Paint paint = new Paint();
private final Bitmap bitmap;
private OnLayerDrawingListener onLayerDrawingListener;
private Layer(Bitmap bitmap) {
this.bitmap = bitmap;
}
private Layer(Bitmap bitmap, OnLayerDrawingListener callback) {
this.bitmap = bitmap;
this.onLayerDrawingListener = callback;
}
public OnLayerDrawingListener getOnLayerDrawingListener() {
return onLayerDrawingListener;
}
public void setOnLayerDrawingListener(OnLayerDrawingListener layerDrawingCallback) {
this.onLayerDrawingListener = layerDrawingCallback;
}
public void setBrendingMode(Mode mode) {
paint.setXfermode(new PorterDuffXfermode(mode));
}
}
public static interface OnLayerDrawingListener {
void draw(Canvas canvas);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment