在今年I/O大会之前,如果要实现圆角或者圆形图片可以自定义View,比如之前的博文《Android 自定义UI View - 03 圆形图片控件》或者通过一些第三方库来实现,比如下面这个:
但是在I/O大会之后,Google发布了新的Support lib,其中有一个是RoundedBitmapDrawable类,通过这个类可以很容易实现圆角和圆形图片。
可以直接在上一个工程的基础上修改部分代码实现,具体实现步骤如下:
1.首先需要添加support-v4依赖
在build.gralde的dependencies中添加下面代码:
1
2
3
4
5
6
7
|
dependencies {
compile
'com.android.support:support-v4:21.+'
compile
'com.android.support:appcompat-v7:21.+'
compile
'com.android.support:support-v4:21.+'
}
|
添加完成后需要同步一下Gradle,同步成功后就可以使用RoundedBitmapDrawable类。
2.创建RoundedBitmapDrawable对象
1
2
3
4
5
|
Bitmap src = BitmapFactory.decodeResource(getResources(), imageId);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), src);
roundedBitmapDrawable.setCornerRadius(
100);
roundedBitmapDrawable.setAntiAlias(
true);
image.setImageDrawable(roundedBitmapDrawable);
|
生成圆角图片只需要根据图片大小设置合理的圆角半径即可,效果如下:
由于RoundedBitmapDrawable
类没有直接提供生成圆形图片的方法,所以生成圆形图片首先需要对原始图片进行裁剪,将图片裁剪成正方形,最后再生成圆形图片,具体实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Bitmap src = BitmapFactory.decodeResource(getResources(), imageId);
Bitmap dst;
if (src.getWidth() >= src.getHeight()){
dst = Bitmap.createBitmap(src, src.getWidth()/
2 - src.getHeight()/
2,
0, src.getHeight(), src.getHeight()
);
}
else{
dst = Bitmap.createBitmap(src,
0, src.getHeight()/
2 - src.getWidth()/
2, src.getWidth(), src.getWidth()
);
}
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), dst);
roundedBitmapDrawable.setCornerRadius(dst.getWidth() /
2);
roundedBitmapDrawable.setAntiAlias(
true);
image.setImageDrawable(roundedBitmapDrawable);
|
这样通过简单的转换就可以将图片裁剪成圆形图片效果如下:
更多关于RoundedBitmapDrawable方法可以参考官方API文档。
参考: