Skip to content

Instantly share code, notes, and snippets.

@BCsl
Created September 19, 2016 06: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 BCsl/3767317bac49ab54f170664b76d025db to your computer and use it in GitHub Desktop.
Save BCsl/3767317bac49ab54f170664b76d025db to your computer and use it in GitHub Desktop.
Round Image Drawable
public class HeaderRoundDrawable extends Drawable {
private static final float ROUND_RADIUS = ScreenUtil.dip2px(AppApplication.getContext(), 6);
private final RectF mRect = new RectF(), mBitmapRect;
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private Path mPath = new Path();
private float[] mRadius;
public HeaderRoundDrawable(Bitmap bitmap) {
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapRect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);
mRadius = new float[]{ROUND_RADIUS, ROUND_RADIUS, ROUND_RADIUS, ROUND_RADIUS, 0, 0, 0, 0};
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRect.set(0, 0, bounds.width(), bounds.height());
// Resize the original bitmap to fit the new bound
Matrix shaderMatrix = new Matrix();
shaderMatrix.setRectToRect(mBitmapRect, mRect, Matrix.ScaleToFit.FILL);
mBitmapShader.setLocalMatrix(shaderMatrix);
}
@Override
public void draw(Canvas canvas) {
mPath.reset();
mPath.addRoundRect(mRect, mRadius, Path.Direction.CCW);
canvas.drawPath(mPath, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment