Android中实现圆角图片的几种方法

来源:互联网 发布:火并软件 编辑:程序博客网 时间:2024/06/04 00:40
  • 1. 最常用的也是最方便的是定义一个带有圆角corner的ImageView。

    代码如下:

    public class RoundImageView extends ImageView {    public RoundImageView(Context context) {        super(context);    }    public RoundImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);    }    @Override    protected void onDraw(Canvas canvas) {        Path clipPath = new Path();        int w = this.getWidth();        int h = this.getHeight();        /**         * RectF  圆角矩形         * **/        clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f,                Path.Direction.CW);        canvas.clipPath(clipPath);        super.onDraw(canvas);    }}

    代码很简单,主要就是调用了canvas的clip方法。
    关于clip方法的基本用法可以参考:Android学习之Canvas之clip方法的Region.Op参数学习

  • 2. 直接对bitmap图片处理,生成一个带圆角的bitmap。

    public static Bitmap getRoundedCornerBitmap(final Bitmap bitmap,                                            final int pixels) {    final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),            bitmap.getHeight(), Bitmap.Config.ARGB_8888);    final Canvas canvas = new Canvas(output);    final int color = 0xff424242;    final Paint paint = new Paint();    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());    final RectF rectF = new RectF(rect);    final float roundPx = pixels;    paint.setAntiAlias(true);    canvas.drawARGB(0, 0, 0, 0);    paint.setColor(color);    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));    canvas.drawBitmap(bitmap, rect, rect, paint);    return output;}

    此方法主要利用了Paint的Xfermode属性来处理,
    具体可参考:android 画图之setXfermode

  • 3. 经常会看到一些带有圆角的item的Listview,这个可以利用shape来实现这样的效果。

    效果图如下:
    这里写图片描述

    可以在drawable目录下定义xml:

    <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android">       <solid android:color="#FFFFFF" />       <corners android:topLeftRadius="10dp"               android:topRightRadius="10dp"                android:bottomRightRadius="10dp"               android:bottomLeftRadius="10dp"/>   </shape>   

    shape相关的属性定义可以参考:Android中shape的使用

    如果需要在代码中动态更新圆角区域的背景颜色,可以在代码中对应的类,比如ShapeDrawable、PaintDrawable等。

    PaintDrawable paintDrawable = new PaintDrawable();paintDrawable.setCornerRadii(new float[] {10, 10, 10, 10});paintDrawable.getPaint().setColor(R.color.bg);paintDrawable.invalidateSelf();
0 0
原创粉丝点击