Android  ImageView绘制圆角效果

所属分类: 软件编程 / Android 阅读数: 20
收藏 0 赞 0 分享

前言

Android 开发中,我们经常需要实现图片的圆形/圆角的效果,我们可以使用两种方式来实现这样的效果。一种是使用Xfermode,另一种是BitmapShader来实现。下面我将分别介绍这两种用法。

使用Xfermode的方式实现
使用该方式的关键代码,如下:

  private Bitmap creataBitmap(Bitmap bitmap) {

    //用指定的一个Bitmap来构建一个画布
    Bitmap target = Bitmap.createBitmap(1000,1000, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    final Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setAntiAlias(true);
    //在刚才的画布上绘制一个圆形区域
    canvas.drawCircle(500,500,500,paint);
    //设置Xfermode,使用SRC_IN模式,这样可以取到第二张图片重叠后的区域
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    //在画布上绘制第二个需要显示的bitmap
    canvas.drawBitmap(bitmap,0,0,paint);
    return target;
  }

上面代码中看出在指定的画布上绘制了两层图像,一个是半径为500像素的圆形,一个是将目标Bitmap绘制在上面。之间还调用了paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));作用是这两个绘制的效果图叠加后,取得第二个图的交集图。所以,我们先绘制一个圆形,然后绘制Bitmap,交集为圆形,取出的就是圆形区域的Bitmap了。
PorterDuff.Mode中一共有16种效果显示,如下:

可以根据不同的Mode,控制显示的效果图。

开始应用

1.自定义属性在attrs.xml中

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <attr name="borderRadius" format="dimension" />
  <attr name="type">
    <enum name="circle" value="0"/>
    <enum name="round" value="1"/>
  </attr>
  <attr name="src" format="reference"/>
  <declare-styleable name="RoundImageView">
    <attr name="borderRadius"/>
    <attr name="type"/>
    <attr name="src"/>
  </declare-styleable>

</resources>

2.自定义View

public class RoundImageView extends View {

  private int type;
  private static final int TYPE_CIRCLE = 0;
  private static final int TYPE_ROUND = 1;
  //图片
  private Bitmap mSrc;
  //圆角大小
  private int mRadius;
  //高度
  private int mWidth;
  //宽度
  private int mHeight;

  public RoundImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //获取自定义的属性
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
    //获取自定以属性的数目
    int count = a.getIndexCount();
    for (int i=0 ; i<count ; i++){
      int attr = a.getIndex(i);
      switch (attr){
        case R.styleable.RoundImageView_borderRadius:
          int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
          mRadius = a.getDimensionPixelSize(attr, defValue);
          break;
        case R.styleable.RoundImageView_type:
          type = a.getInt(attr,0);
          break;
        case R.styleable.RoundImageView_src:
          mSrc = BitmapFactory.decodeResource(getResources(),a.getResourceId(attr,0));
          break;
      }
    }

    a.recycle();
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    //设置宽度
    int specMode = MeasureSpec.getMode(widthMeasureSpec);
    int specSize = MeasureSpec.getSize(widthMeasureSpec);
    if (specMode == MeasureSpec.EXACTLY){
      mWidth = specSize;
    }else {
      int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth();
      if (specMode == MeasureSpec.AT_MOST)// wrap_content
      {
        mWidth = Math.min(desireByImg, specSize);
      } else
        mWidth = desireByImg;
    }

    //设置高度
    specMode = MeasureSpec.getMode(heightMeasureSpec);
    specSize = MeasureSpec.getSize(heightMeasureSpec);
    if (specMode == MeasureSpec.EXACTLY){
      mHeight = specSize;
    }else {
      int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight();
      if (specMode == MeasureSpec.AT_MOST)// wrap_content
      {
        mHeight = Math.min(desire, specSize);
      } else
        mHeight = desire;
    }

    setMeasuredDimension(mWidth,mHeight);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    switch (type){
      case TYPE_CIRCLE:
        int min = Math.min(mWidth,mHeight);
        //从当前存在的Bitmap,按一定的比例创建一个新的Bitmap。
        mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false);
        canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);

        break;
      case TYPE_ROUND:
        mSrc = Bitmap.createScaledBitmap(mSrc, mWidth, mHeight, false);
        canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);

        break;
    }
  }

  /**
   * 绘制圆角
   * @param source
   * @return
   */
  private Bitmap createRoundConerImage(Bitmap source) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    RectF rect = new RectF(0, 0, mWidth, mHeight);
    canvas.drawRoundRect(rect, mRadius, mRadius, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }

  /**
   * 绘制圆形
   * @param source
   * @param min
   * @return
   */
  private Bitmap createCircleImage(Bitmap source, int min) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    canvas.drawCircle(min/2,min/2,min/2,paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }
}

3.布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:roundview="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:id="@+id/activity_main"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:padding="10dp"
       tools:context="mo.yumf.com.myviews.MainActivity">


  <mo.yumf.com.myviews.RoundImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="20dp"
    roundview:borderRadius="10dp"
    roundview:src="@drawable/ac_default_icon"
    roundview:type="round"/>

  <mo.yumf.com.myviews.RoundImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="20dp"
    roundview:src="@drawable/ac_default_icon"
    roundview:type="circle"/>
</LinearLayout>

上面的自定义View中,存在一个局限,那就是只能在布局中设置要加载的图片资源,不能在代码中设置图片。下面我们使用同样的方式,选择自定义ImageView来实现。

public class RoundImageView extends ImageView {

  private int type;
  private static final int TYPE_CIRCLE = 0;
  private static final int TYPE_ROUND = 1;
  //图片
  private Bitmap mSrc;
  //圆角大小
  private int mRadius;

  public RoundImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //获取自定义的属性
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RoundImageView);
    //获取自定以属性的数目
    int count = a.getIndexCount();
    for (int i=0 ; i<count ; i++){
      int attr = a.getIndex(i);
      switch (attr){
        case R.styleable.RoundImageView_borderRadius:
          int defValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
          mRadius = a.getDimensionPixelSize(attr, defValue);
          break;
        case R.styleable.RoundImageView_type:
          type = a.getInt(attr,0);
          break;
      }
    }

    a.recycle();
  }

  @Override
  protected void onDraw(Canvas canvas) {
    if (getDrawable() != null){
      Bitmap bitmap = getBitmap(getDrawable());
      if (bitmap != null){
        switch (type){
          case TYPE_CIRCLE:
            //获取ImageView中的宽高,取最小值
            int min = Math.min(getMeasuredWidth(),getMeasuredHeight());
            //从当前存在的Bitmap,按一定的比例创建一个新的Bitmap。
            mSrc = Bitmap.createScaledBitmap(bitmap, min, min, false);
            canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);

            break;
          case TYPE_ROUND:
            mSrc = Bitmap.createScaledBitmap(bitmap, getMeasuredWidth(), getMeasuredHeight(), false);
            canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);

            break;
        }
      }
    }else {

      super.onDraw(canvas);
    }
  }

  private Bitmap getBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable){
      return ((BitmapDrawable)drawable).getBitmap();
    }else if (drawable instanceof ColorDrawable){
      Rect rect = drawable.getBounds();
      int width = rect.right - rect.left;
      int height = rect.bottom - rect.top;
      int color = ((ColorDrawable)drawable).getColor();
      Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      canvas.drawARGB(Color.alpha(color),Color.red(color), Color.green(color), Color.blue(color));
      return bitmap;
    }else {
      return null;
    }
  }


  /**
   * 绘制圆角
   * @param source
   * @return
   */
  private Bitmap createRoundConerImage(Bitmap source) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    RectF rect = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
    canvas.drawRoundRect(rect, mRadius, mRadius, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }

  /**
   * 绘制圆形
   * @param source
   * @param min
   * @return
   */
  private Bitmap createCircleImage(Bitmap source, int min) {
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(target);
    canvas.drawCircle(min/2,min/2,min/2,paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);
    return target;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Android实现悬浮窗体效果

这篇文章主要为大家详细介绍了Android实现悬浮窗体效果,显示悬浮窗口,窗口可以拖动,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Andriod studio 打包aar 的方法

这篇文章主要介绍了Andriod studio 打包aar的方法,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下
收藏 0 赞 0 分享

Android加载loading对话框的功能及实例代码(不退出沉浸式效果)

这篇文章主要介绍了Android加载loading对话框的功能及实例代码,不退出沉浸式效果,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中LayoutInflater.inflater()的正确打开方式

这篇文章主要给大家介绍了关于Android中LayoutInflater.inflater()的正确打开方式,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Delphi在Android下使用Java库的方法

这篇文章主要介绍了Delphi在Android下使用Java库的方法,本文以Android的USB串口通讯库为例,给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Retrofit2日志拦截器的使用

这篇文章主要介绍了Retrofit2日志拦截器的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android创建外部lib库及自定义View的图文教程

这篇文章主要给大家介绍了关于Android创建外部lib库及自定义View的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android分享微信小程序失败的一些事小结

这篇文章主要给大家介绍了关于Android分享微信小程序失败一些事,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android分享微信小程序技巧之图片优化

这篇文章主要给大家介绍了关于Android分享微信小程序技巧之图片优化的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android Viewpager实现无限循环轮播图

这篇文章主要为大家详细介绍了Android Viewpager实现无限循环轮播图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多