Android 自定义Drawable 实现圆角矩形和圆形图片

一,自定义圆角矩形Drawable

public class RoundRectImageDrawable extends Drawable {

private Bitmap mBitmap;
private Paint mPaint;
private RectF rectF;

public RoundRectImageDrawable(Bitmap bitmap) {

    mBitmap = bitmap;
    BitmapShader mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShader(mBitmapShader);
    rectF = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());

}

@Override
public void setBounds(int left, int top, int right, int bottom) {
    super.setBounds(left, top, right, bottom);
    rectF = new RectF(left, top, right, bottom);
}

@Override
public void draw(@NonNull Canvas canvas) {
    //(@NonNull RectF rect, float rx, float ry, @NonNull Paint paint)
    canvas.drawRoundRect(rectF, 15, 15 ,mPaint);
}

@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
    mPaint.setAlpha(alpha);
}

@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
    mPaint.setColorFilter(colorFilter);
}

@Override
public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}

@Override
public int getIntrinsicWidth() {
    return mBitmap.getWidth();
}

@Override
public int getIntrinsicHeight() {
    return mBitmap.getHeight();
}

}

你可能感兴趣的:(android)