Android设置图片圆角的方法

Android设置图片圆角的方法,第1张

Android中经常会遇到对图片进行二次处理,例如加圆角,或者显示圆形图片

通过第三方框架Glide实现图片显示有圆角,有三种写法如下:

1.1、第一种实现:

1.2、第二种实现:

1.3、第三种实现:

自定义ImageView:

对图片进行处理,此方法还可以加边框

实现圆形和边框:

以上就是本文的全部内容,希望对大家的学习有所帮助!

我们要实现的图片控件继承自 AppCompatImageView ,它是 ImageView 的子类,但提供了更好的兼容性,我们在此基础上添加了若干自定义的属性和方法以实现最终的 NiceImageView :

要实圆角或者圆形的显示效果,就是对图片显示的内容区域进行“裁剪”,只显示指定的区域即可。如何做呢?

一种比较直接的办法是这样的,由于图片是被绘制在画布上的,所以用 canvas 的 clipPath() 方法先将画布裁剪成指定形状,这样就能让图片按指定形状显示了,重新 draw() 方法即可:

这样使用 src 、 background 属性给ImageView设置显示的图片都能达到预期的显示效果。但是由于 clipPath() 方法不支持抗锯齿,图片边缘会有明显的毛糙感,体验并不理想,所以需要寻找其它方法。

另一种方法是使用图像的 Alpha 合成模式 ,即

PorterDuff 来实现, 官方文档 。这里我们使用其中的 DST_IN 模式。整个过程就是先绘制目标图像,也就是图片;再绘制原图像,即一个圆角矩形或者圆形,这样最终目标图像只显示和原图像重合的区域。

到这里就实现了显示为圆角或者圆形了。但是需要通过 src 属性或者对应的方法来设置图片,否则不能达到预期效果。

绘制边框就相对容易理解了,只需要绘制一个指定样式的圆角矩形或者圆形即可:

当图片显示为圆形时,还可以绘制一个内边框,但圆角矩形的话由于圆角大小的问题,目前只能设置一个边框咯。

但是有个问题,绘制的边框会覆盖在图片上,如果边框太宽会导致图片的可见区域变小了,影像显示效果,像这样,左下角的花盆不见了:

那么如何让边框不覆盖在图片上呢?可以在 Alpha 合成绘制前先将画布缩小一定比例,最后再绘制边框,这样问题就解决了。

缩放后的ImageView显示区域的宽高就是原宽、高分别减去2倍的边框宽度,这样缩小的比例也就显而易见了。效果如下,左下角的花盆出来了:

遮罩可以理解为一层带透明度的颜色,遮罩默认不绘制,当制定了遮罩颜色时才会绘制,实现很简单:

例如加一个透明度30%的红色遮罩后的效果:

核心的实现逻辑就这些了,剩下的就是自定义属性和方法了,有兴趣的可以看源码,都很简单,希望对你有所帮助吧!

更多细节及用法见GitHub: https://github.com/SheHuan/NiceImageView

如果你需要实现类似钉钉的圆形组合头像,例如:

本文链接:https://blog.csdn.net/weixin_37577039/article/details/79090433

```

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

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/colorAccent" />

    <!-- 这里是设置为四周 也可以单独设置某个位置为圆角-->

    <corners android:topLeftRadius="5dp"

        android:topRightRadius="5dp"

        android:bottomRightRadius="5dp"

        android:bottomLeftRadius="5dp"/>

    <stroke android:width="1dp" android:color="#000000" />

</shape

```

```

<?xml version="1.0" encoding="UTF-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">   

<!-- 边框颜色值 -->

<item>   

      <shape>   

            <solid android:color="#3bbaff" />   

      </shape>   

</item>   

<!--这个是按钮边框设置为四周 并且宽度为1-->

<item

android:right="1dp"

android:left="1dp"

android:top="1dp"

android:bottom="1dp">

    <shape>   

<!--这个是背景颜色-->

          <solid android:color="#ffffff" />       

<!--这个是按钮中的字体与按钮内的四周边距-->

          <padding android:bottom="10dp"   

                android:left="10dp"   

                android:right="10dp"   

                android:top="10dp" />   

    </shape>       

</item>   

</layer-list>

```

使用:

```android:background="@drawable/button_edge"```

```

<?xml version="1.0" encoding="UTF-8"?>

<shape

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">

    <!-- 填充的颜色 -->

    <solid android:color="#FFFFFF" />

    <!-- android:radius 弧形的半径 -->

    <!-- 设置按钮的四个角为弧形 -->

    <corners

    android:radius="5dip" /> 

    <!--也可单独设置-->

    <!-- <corners -->

  <!-- android:topLeftRadius="10dp"-->

  <!-- android:topRightRadius="10dp"-->

  <!-- android:bottomRightRadius="10dp"-->

  <!--  android:bottomLeftRadius="10dp"-->

<!--  />  -->

        **设置文字padding**

    <!-- padding:Button里面的文字与Button边界的间隔 -->

    <padding

        android:left="10dp"

        android:top="10dp"

        android:right="10dp"

        android:bottom="10dp"

        />

</shape>

```

```

<?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>

```

使用:

```

android:background="@drawable/image_circle"

```

```

Glide.with(MainActivity.this).load(croppedUri)

.transform(new GlideRectRound(MainActivity.this,6)).into(headIcon)

```

```

import android.content.Context

import android.content.res.Resources

import android.graphics.Bitmap

import android.graphics.BitmapShader

import android.graphics.Canvas

import android.graphics.Paint

import android.graphics.RectF

import android.util.Log

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool

import com.bumptech.glide.load.resource.bitmap.BitmapTransformation

/**

* Created by SiHao on 2018/3/3.

* Glide 的 圆角 图片 工具类

*/

public class GlideRectRound extends BitmapTransformation {

    private static float radius = 0f

    // 构造方法1 无传入圆角度数 设置默认值为5

    public GlideRectRound(Context context) {

        this(context, 5)

    }

    // 构造方法2 传入圆角度数

    public GlideRectRound(Context context, int dp) {

        super(context)

        // 设置圆角度数

        radius = Resources.getSystem().getDisplayMetrics().density * dp

    }

    // 重写该方法 返回修改后的Bitmap

    @Override

    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {

        return rectRoundCrop(pool,toTransform)

    }

    @Override

    public String getId() {

        Log.e("getID",getClass().getName() + Math.round(radius))

        return getClass().getName() + Math.round(radius)  // 四舍五入

    }

    private Bitmap rectRoundCrop(BitmapPool pool, Bitmap source){

        if (source == null) return null

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888)// ARGB_4444——代表4x4位ARGB位图,ARGB_8888——代表4x8位ARGB位图

        if (result == null) {

            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888)

        }

        Canvas canvas = new Canvas(result)

        Paint paint = new Paint()

        // setShader 对图像进行渲染

        // 子类之一 BitmapShader设置Bitmap的变换  TileMode 有CLAMP (取bitmap边缘的最后一个像素进行扩展),REPEAT(水平地重复整张bitmap)

        //MIRROR(和REPEAT类似,但是每次重复的时候,将bitmap进行翻转)

        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP))

        paint.setAntiAlias(true)  // 抗锯齿

        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight())

        canvas.drawRoundRect(rectF, radius, radius, paint)

        return result

    }

}

```

圆角:

```

import android.content.Context

import android.graphics.Bitmap

import android.graphics.BitmapShader

import android.graphics.Canvas

import android.graphics.Paint

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool

import com.bumptech.glide.load.resource.bitmap.BitmapTransformation

/**

* Created by SiHao on 2018/3/3.

* Glide圆形图片工具类

*/

public class GlideCircleBitmap extends BitmapTransformation{

    public GlideCircleBitmap(Context context) {

        super(context)

    }

    // 重写该方法 返回修改后的Bitmap

    @Override

    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {

        return circleCrop(pool, toTransform)

    }

    @Override

    public String getId() {

        return getClass().getName()

    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {

        if (source == null) return null

        // 边长取长宽最小值

        int size = Math.min(source.getWidth(), source.getHeight())

        int x = (source.getWidth() - size) / 2

        int y = (source.getHeight() - size) / 2

        // TODO this could be acquired from the pool too

        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size)

        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888)// ARGB_4444——代表4x4位ARGB位图,ARGB_8888——代表4x8位ARGB位图

        if (result == null) {

            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)

        }

        Canvas canvas = new Canvas(result)

        Paint paint = new Paint()

        // setShader 对图像进行渲染

        // 子类之一 BitmapShader设置Bitmap的变换  TileMode 有CLAMP (取bitmap边缘的最后一个像素进行扩展),REPEAT(水平地重复整张bitmap)

        //MIRROR(和REPEAT类似,但是每次重复的时候,将bitmap进行翻转)

        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP))

        paint.setAntiAlias(true)// 抗锯齿

        // 半径取 size的一半

        float r = size / 2f

        canvas.drawCircle(r, r, r, paint)

        return result

    }

}

```

```

URL url = new URL(String类型的字符串) //将String类型的字符串转换为URL格式

holder.UserImage.setImageBitmap(BitmapFactory.decodeStream(url.openStream()))

```

```

//得到资源文件的BitMap

Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.dog)

//创建RoundedBitmapDrawable对象

RoundedBitmapDrawable roundImg =RoundedBitmapDrawableFactory.create(getResources(),image)

//抗锯齿

roundImg.setAntiAlias(true)

//设置圆角半径

roundImg.setCornerRadius(30)

//设置显示图片

imageView.setImageDrawable(roundImg)

```

```

//如果是圆的时候,我们应该把bitmap图片进行剪切成正方形, 然后再设置圆角半径为正方形边长的一半即可

  Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.dog)

  Bitmap bitmap = null

  //将长方形图片裁剪成正方形图片

  if (image.getWidth() == image.getHeight()) {

      bitmap = Bitmap.createBitmap(image, image.getWidth() / 2 - image.getHeight() / 2, 0, image.getHeight(), image.getHeight())

  } else {

      bitmap = Bitmap.createBitmap(image, 0, image.getHeight() / 2 - image.getWidth() / 2, image.getWidth(), image.getWidth())

  }

  RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap)

  //圆角半径为正方形边长的一半

  roundedBitmapDrawable.setCornerRadius(bitmap.getWidth() / 2)

  //抗锯齿

  roundedBitmapDrawable.setAntiAlias(true)

  imageView.setImageDrawable(roundedBitmapDrawable)

```


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11118294.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存