Created
November 16, 2017 06:44
-
-
Save daolq3012/e88a60908069f6aff5cbed6712a4e263 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* RoundLayout | |
*/ | |
public class RoundLayout extends RelativeLayout { | |
private Bitmap mMaskBitmap; | |
private Paint mPaint; | |
private Paint mMaskPaint; | |
private float mCornerRadius; | |
private boolean isCircle = false; | |
public RoundLayout(Context context) { | |
super(context); | |
init(null, 0); | |
} | |
public RoundLayout(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(attrs, 0); | |
} | |
public RoundLayout(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
init(attrs, defStyle); | |
} | |
private void init(AttributeSet attrs, int defStyle) { | |
if (attrs != null) { | |
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.RoundLayout); | |
mCornerRadius = (float) ta.getDimensionPixelSize(R.styleable.RoundLayout_roundRadius, | |
(int) mCornerRadius); | |
isCircle = ta.getBoolean(R.styleable.RoundLayout_isRoundCircle, isCircle); | |
ta.recycle(); | |
} | |
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
mMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); | |
mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); | |
setWillNotDraw(false); | |
} | |
@Override | |
protected void onSizeChanged(int w, int h, int oldw, int oldh) { | |
super.onSizeChanged(w, h, oldw, oldh); | |
mMaskBitmap = createMask(w, h); | |
} | |
@Override | |
public void draw(Canvas canvas) { | |
if (isInEditMode()) { | |
super.draw(canvas); | |
return; | |
} | |
Bitmap offscreenBitmap = | |
Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888); | |
Canvas offscreenCanvas = new Canvas(offscreenBitmap); | |
super.draw(offscreenCanvas); | |
if (mMaskBitmap == null) { | |
mMaskBitmap = createMask(canvas.getWidth(), canvas.getHeight()); | |
} | |
offscreenCanvas.drawBitmap(mMaskBitmap, 0f, 0f, mMaskPaint); | |
canvas.drawBitmap(offscreenBitmap, 0f, 0f, mPaint); | |
} | |
private Bitmap createMask(int width, int height) { | |
if (isCircle) { | |
mCornerRadius = Math.min(width, height) / 2; | |
} | |
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8); | |
Canvas canvas = new Canvas(mask); | |
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
paint.setColor(Color.WHITE); | |
canvas.drawRect(0, 0, width, height, paint); | |
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); | |
canvas.drawRoundRect(new RectF(0, 0, width, height), mCornerRadius, mCornerRadius, paint); | |
return mask; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment