您的位置:首页 > 移动开发 > Android开发

Android-->圆角图片,圆角任意View,圆角父布局Layout(任意形状的View且超简洁实现)

2016-04-17 00:41 639 查看
相信大家对圆角图片已经非常熟悉了,但是圆角任意View,和圆角父布局,甚至是任意形状的View,肯定还是比较陌生的.

今天就揭开她的面纱.

圆角图片移步:/article/1345568.html

View的Draw过程移步:/article/7934724.html

//通常情况下,圆角图片是这样的...
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;
}


上图为证:



其实最核心的代码,就一行.(真的是对得起标题, 超简洁的实现啊…..)

在View的draw方法中,加入:(这个方法可以在任意一个View的子类中添加,包括ImageView)

@Override
public void draw(Canvas canvas) {
//roundPath是什么形状,绘制出来的Layout就是什么形状的....相当于任意View了.
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);//如果你继承的是ViewGroup,注意此行,否则draw方法是不会回调的;
roundPath = new Path();
rectF = new RectF();
}

private void setRoundPath() {
//添加一个圆角矩形到path中, 如果要实现任意形状的View, 只需要手动添加path就行
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);
}
}


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 欢迎您的加入.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: