相信大家对圆角图片已经非常熟悉了,但是圆角任意View,和圆角父布局,甚至是任意形状的View,肯定还是比较陌生的.
今天就揭开她的面纱.
圆角图片移步:http://blog.csdn.net/lmj623565791/article/details/24555655
View的Draw过程移步:http://blog.csdn.net/fener10289/article/details/8231712
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx,
int number) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xdd424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
number = number * 255 / 100;
paint.setAlpha(number);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
上图为证:
其实最核心的代码,就一行.(真的是对得起标题, 超简洁的实现啊…..)
在View的draw方法中,加入:(这个方法可以在任意一个View的子类中添加,包括ImageView)
@Override
public void draw(Canvas canvas) {
canvas.clipPath(roundPath);
super.draw(canvas);
}
以下是我的使用方式:
public class RoundLayout extends RelativeLayout {
private float roundLayoutRadius = 14f;
private Path roundPath;
private RectF rectF;
public RoundLayout(Context context) {
this(context, null);
}
public RoundLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundLayout);
roundLayoutRadius = typedArray.getDimensionPixelSize(R.styleable.RoundLayout_roundLayoutRadius, (int) roundLayoutRadius);
typedArray.recycle();
init();
}
private void init() {
setWillNotDraw(false);
roundPath = new Path();
rectF = new RectF();
}
private void setRoundPath() {
roundPath.addRoundRect(rectF, roundLayoutRadius, roundLayoutRadius, Path.Direction.CW);
}
public void setRoundLayoutRadius(float roundLayoutRadius) {
this.roundLayoutRadius = roundLayoutRadius;
setRoundPath();
postInvalidate();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
rectF.set(0f, 0f, getMeasuredWidth(), getMeasuredHeight());
setRoundPath();
}
@Override
public void draw(Canvas canvas) {
if (roundLayoutRadius > 0f) {
canvas.clipPath(roundPath);
}
super.draw(canvas);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
ImageView的圆角,其实也是那一行代码可以搞定的.不阐述了,快快行动,用行动证明自己吧.
补充:
上述方法会有明显的锯齿情况,因为Paint才提供抗锯齿方法.
解决方法: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2016/0420/4167.html
源代码移步:
https://github.com/angcyo/RoundAngleFrameLayout/blob/master/app/src/main/java/com/ybao/rf/RoundAngleFrameLayout.java
至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.