使用RoundedBitmapDrawable快速生成圆角和圆形图片

来源:互联网 发布:模拟太阳系的软件 编辑:程序博客网 时间:2024/05/13 01:19

转自:http://blog.csdn.net/hahashui123/article/details/46929909

在今年I/O大会之前,如果要实现圆角或者圆形图片可以自定义View,比如之前的博文《Android 自定义UI View - 03 圆形图片控件》或者通过一些第三方库来实现,比如下面这个:

  • RoundedImageView by vinc3m1

但是在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); //获取Bitmap图片
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), src); //创建RoundedBitmapDrawable对象
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文档。

参考:

  • RoundedBitmapDrawable API

  • Google I/O 2014 – What’s New In Android


0 0
原创粉丝点击