Skip to content

Instantly share code, notes, and snippets.

@DHuckaby
Created October 19, 2012 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DHuckaby/3919956 to your computer and use it in GitHub Desktop.
Save DHuckaby/3919956 to your computer and use it in GitHub Desktop.
A drawable wrapper that caches the drawing layer, used for caching gradients on older devices.
public class CachingDrawable extends Drawable {
private final Drawable mDrawable;
private final Config mConfig;
private Bitmap mBitmap;
public CachingDrawable(Drawable drawable) {
this(drawable, Config.ARGB_8888);
}
public CachingDrawable(Drawable drawable, Config config) {
mDrawable = drawable;
mConfig = config;
}
@Override
public void draw(Canvas canvas) {
if (mBitmap == null) {
Rect bounds = getBounds();
int height = bounds.height();
int width = bounds.width();
if (height > 0 && width > 0) {
mDrawable.setBounds(bounds);
mBitmap = Bitmap.createBitmap(width, height, mConfig);
mDrawable.draw(new Canvas(mBitmap));
canvas.drawBitmap(mBitmap, 0, 0, null);
} else {
invalidateSelf();
}
} else {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
}
@Override
public int getOpacity() {
return mConfig == Config.RGB_565 ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
mDrawable.setAlpha(alpha);
mBitmap = null;
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter cf) {
mDrawable.setColorFilter(cf);
mBitmap = null;
invalidateSelf();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment