怎么在Android中利用ImageView将图片进行圆形、圆角处理

发布时间:2020-11-27 17:20:47 作者:Leah
来源:亿速云 阅读:402

本篇文章给大家分享的是有关怎么在Android中利用ImageView将图片进行圆形、圆角处理,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

基本思路是,自定义一个ImageView,通过重写onDraw方法画出一个圆形的图片来:

public class ImageViewPlus extends ImageView{
  private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Bitmap mRawBitmap;
  private BitmapShader mShader;
  private Matrix mMatrix = new Matrix();
  
  public ImageViewPlus(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  
  @Override
  protected void onDraw(Canvas canvas) {
    Bitmap rawBitmap = getBitmap(getDrawable());
    if (rawBitmap != null){
      int viewWidth = getWidth();
      int viewHeight = getHeight();
      int viewMinSize = Math.min(viewWidth, viewHeight);
      float dstWidth = viewMinSize;
      float dstHeight = viewMinSize;
      if (mShader == null || !rawBitmap.equals(mRawBitmap)){
        mRawBitmap = rawBitmap;
        mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
      }
      if (mShader != null){
        mMatrix.setScale(dstWidth / rawBitmap.getWidth(), dstHeight / rawBitmap.getHeight());
        mShader.setLocalMatrix(mMatrix);
      }
      mPaintBitmap.setShader(mShader);
      float radius = viewMinSize / 2.0f;
      canvas.drawCircle(radius, radius, radius, mPaintBitmap);
    } 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;
    }
  }
}

分析一下代码:

 canvas.drawCircle 决定了画出来的形状是圆形,而圆形的内容则是通过 mPaintBitmap.setShader 搞定的。

其中,BitmapShader需要设置Bitmap填充ImageView的方式(CLAMP:拉伸边缘, MIRROR:镜像, REPEAT:整图重复)。

这里其实设成什么不重要,因为我们实际需要的是将Bitmap按比例缩放成跟ImageView一样大,而不是预置的三种效果。

所以,别忘了 mMatrix.setScale 和 mShader.setLocalMatrix 一起用,将图片缩放一下。

四、支持边框

public class ImageViewPlus extends ImageView{
  private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Bitmap mRawBitmap;
  private BitmapShader mShader;
  private Matrix mMatrix = new Matrix();
  private float mBorderWidth = dip2px(15);
  private int mBorderColor = 0xFF0080FF;
  
  public ImageViewPlus(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  
  @Override
  protected void onDraw(Canvas canvas) {
    Bitmap rawBitmap = getBitmap(getDrawable());
    if (rawBitmap != null){
      int viewWidth = getWidth();
      int viewHeight = getHeight();
      int viewMinSize = Math.min(viewWidth, viewHeight);
      float dstWidth = viewMinSize;
      float dstHeight = viewMinSize;
      if (mShader == null || !rawBitmap.equals(mRawBitmap)){
        mRawBitmap = rawBitmap;
        mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
      }
      if (mShader != null){
        mMatrix.setScale((dstWidth - mBorderWidth * 2) / rawBitmap.getWidth(), (dstHeight - mBorderWidth * 2) / rawBitmap.getHeight());
        mShader.setLocalMatrix(mMatrix);
      }
      mPaintBitmap.setShader(mShader);
      mPaintBorder.setStyle(Paint.Style.STROKE);
      mPaintBorder.setStrokeWidth(mBorderWidth);
      mPaintBorder.setColor(mBorderColor);
      float radius = viewMinSize / 2.0f;
      canvas.drawCircle(radius, radius, radius - mBorderWidth / 2.0f, mPaintBorder);
      canvas.translate(mBorderWidth, mBorderWidth);
      canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
    } 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;
    }
  }
  
  private int dip2px(int dipVal)
  {
    float scale = getResources().getDisplayMetrics().density;
    return (int)(dipVal * scale + 0.5f);
  }
}

看代码中,加边框实际上就是用实心纯色的 Paint 画了一个圆边,在此基础上画上原来的头像即可。

需要的注意的地方有三个:

1)、圆框的半径不是 radius ,而应该是 radius - mBorderWidth / 2.0f 。想象着拿着笔去画线,线其实是画在右图中白色圈的位置,只不过它很粗。

2)、在ImageView大小不变的基础上,头像的实际大小要比没有边框的时候小了,所以 mMatrix.setScale 的时候要把边框的宽度去掉。

3)、画头像Bitmap的时候不能直接 canvas.drawCircle(radius, radius, radius - mBorderWidth, mPaintBitmap) ,这样你会发现头像的右侧和下方边缘被拉伸了(右图)

为什么呢?因为 Paint 默认是以左上角为基准开始绘制的,此时头像的实际区域是右图中的红框,而超过红框的部分(圆形的右侧和下方),自然被 TileMode.CLAMP效果沿边缘拉伸了。

所以,需要通过挪动坐标系的位置和调整圆心,才能把头像画在正确的区域(右图绿框)中。

五、更多玩法 —— 支持xml配置

既然有了边框,那如果想配置边框的宽度和颜色该如何是好呢?

基本上两个思路:

1)、给ImageViewPlus加上set接口,设置完成之后通过 invalidate(); 重绘一下即可;

2)、在xml里就支持配置一些自定义属性,这样用起来会方便很多。

这里重点说一下支持xml配置自定义属性。

自定义控件要支持xml配置自定义属性的话,首先需要在 \res\values 里去定义属性:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
  <attr name="borderColor" format="color" />
  <attr name="borderWidth" format="dimension" />

  <declare-styleable name="ImageViewPlus"> 
    <attr name="borderColor" />
    <attr name="borderWidth" />
  </declare-styleable> 
</resources>

 然后在ImageViewPlus的构造函数中去读取这些自定义属性:

private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
  private static final int DEFAULT_BORDER_WIDTH = 0;
  
  public ImageViewPlus(Context context, AttributeSet attrs) {
    super(context, attrs);
    //取xml文件中设定的参数
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
    mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
    mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
    ta.recycle();
  }

 在xml布局中使用自定义属性:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:snser="http://schemas.android.com/apk/res/cc.snser.imageviewplus"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/wallpaper"
  android:orientation="vertical"
  tools:context="${relativePackage}.${activityClass}" >
  
  <cc.snser.imageviewplus.ImageViewPlus
    android:id="@+id/imgplus"
    android:layout_width="200dp"
    android:layout_height="300dp"
    android:layout_marginBottom="50dp"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:src="@drawable/img_square"
    snser:borderColor="#FF0080FF"
    snser:borderWidth="15dp" />
  
</RelativeLayout>

六、 圆角ImageView

其实原理上一样,把 canvas.drawCircle 对应改成 canvas.drawRoundRect 就OK了,直接贴代码吧:

public class ImageViewPlus extends ImageView{
  /**
   * android.widget.ImageView
   */
  public static final int TYPE_NONE = 0;
  /**
   * 圆形
   */
  public static final int TYPE_CIRCLE = 1;
  /**
   * 圆角矩形
   */
  public static final int TYPE_ROUNDED_RECT = 2;  
  
  private static final int DEFAULT_TYPE = TYPE_NONE;
  private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
  private static final int DEFAULT_BORDER_WIDTH = 0;
  private static final int DEFAULT_RECT_ROUND_RADIUS = 0;
  
  private int mType;
  private int mBorderColor;
  private int mBorderWidth;
  private int mRectRoundRadius;
  
  private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
  
  private RectF mRectBorder = new RectF();
  private RectF mRectBitmap = new RectF();
  
  private Bitmap mRawBitmap;
  private BitmapShader mShader;
  private Matrix mMatrix = new Matrix();
  
  public ImageViewPlus(Context context, AttributeSet attrs) {
    super(context, attrs);
    //取xml文件中设定的参数
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
    mType = ta.getInt(R.styleable.ImageViewPlus_type, DEFAULT_TYPE);
    mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
    mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
    mRectRoundRadius = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_rectRoundRadius, dip2px(DEFAULT_RECT_ROUND_RADIUS));
    ta.recycle();
  }
  
  @Override
  protected void onDraw(Canvas canvas) {
    Bitmap rawBitmap = getBitmap(getDrawable());
    
    if (rawBitmap != null && mType != TYPE_NONE){
      int viewWidth = getWidth();
      int viewHeight = getHeight();
      int viewMinSize = Math.min(viewWidth, viewHeight);
      float dstWidth = mType == TYPE_CIRCLE ? viewMinSize : viewWidth;
      float dstHeight = mType == TYPE_CIRCLE ? viewMinSize : viewHeight;
      float halfBorderWidth = mBorderWidth / 2.0f;
      float doubleBorderWidth = mBorderWidth * 2;
      
      if (mShader == null || !rawBitmap.equals(mRawBitmap)){
        mRawBitmap = rawBitmap;
        mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
      }
      if (mShader != null){
        mMatrix.setScale((dstWidth - doubleBorderWidth) / rawBitmap.getWidth(), (dstHeight - doubleBorderWidth) / rawBitmap.getHeight());
        mShader.setLocalMatrix(mMatrix);
      }
      
      mPaintBitmap.setShader(mShader);
      mPaintBorder.setStyle(Paint.Style.STROKE);
      mPaintBorder.setStrokeWidth(mBorderWidth);
      mPaintBorder.setColor(mBorderWidth > 0 ? mBorderColor : Color.TRANSPARENT);
      
      if (mType == TYPE_CIRCLE){
        float radius = viewMinSize / 2.0f;
        canvas.drawCircle(radius, radius, radius - halfBorderWidth, mPaintBorder);
        canvas.translate(mBorderWidth, mBorderWidth);
        canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
      } else if (mType == TYPE_ROUNDED_RECT){
        mRectBorder.set(halfBorderWidth, halfBorderWidth, dstWidth - halfBorderWidth, dstHeight - halfBorderWidth);
        mRectBitmap.set(0.0f, 0.0f, dstWidth - doubleBorderWidth, dstHeight - doubleBorderWidth);
        float borderRadius = mRectRoundRadius - halfBorderWidth > 0.0f ? mRectRoundRadius - halfBorderWidth : 0.0f;
        float bitmapRadius = mRectRoundRadius - mBorderWidth > 0.0f ? mRectRoundRadius - mBorderWidth : 0.0f;
        canvas.drawRoundRect(mRectBorder, borderRadius, borderRadius, mPaintBorder);
        canvas.translate(mBorderWidth, mBorderWidth);
        canvas.drawRoundRect(mRectBitmap, bitmapRadius, bitmapRadius, mPaintBitmap);
      }
    } else {
      super.onDraw(canvas);
    }
  }

  private int dip2px(int dipVal)
  {
    float scale = getResources().getDisplayMetrics().density;
    return (int)(dipVal * scale + 0.5f);
  }
  
  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;
    }
  }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:snser="http://schemas.android.com/apk/res/cc.snser.imageviewplus"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/wallpaper"
  android:orientation="vertical"
  tools:context="${relativePackage}.${activityClass}" >
  
  <cc.snser.imageviewplus.ImageViewPlus
    android:id="@+id/imgplus"
    android:layout_width="200dp"
    android:layout_height="300dp"
    android:layout_marginBottom="50dp"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:src="@drawable/img_rectangle"
    snser:type="rounded_rect"
    snser:borderColor="#FF0080FF"
    snser:borderWidth="10dp"
    snser:rectRoundRadius="30dp" />
  
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
  <attr name="type"> 
    <enum name="none" value="0" /> 
    <enum name="circle" value="1" /> 
    <enum name="rounded_rect" value="2" />
  </attr>
  <attr name="borderColor" format="color" />
  <attr name="borderWidth" format="dimension" />
  <attr name="rectRoundRadius" format="dimension" />

  <declare-styleable name="ImageViewPlus"> 
    <attr name="type" />
    <attr name="borderColor" />
    <attr name="borderWidth" />
    <attr name="rectRoundRadius" />
  </declare-styleable>
</resources>

以上就是怎么在Android中利用ImageView将图片进行圆形、圆角处理,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在android中通过自定义imageview实现一个圆角图片
  2. Android实现圆形图片或者圆角图片

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android imageview age

上一篇:在Java中怎么将 Base64编码与String字符串进行转换

下一篇:怎么在Android中利用TextView实现一个跑马灯效果

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》