日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時間:2025/4/16 编程问答 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用RoundedBitmapDrawable快速生成圆角和圆形图片 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

原文出處:http://www.tuicool.com/articles/eIBbArA

上一篇 《[Material Design]使用Palette類提取圖片的顏色信息》 主要介紹了如何提取圖片的一些特定顏色,不過如果你稍微注意一下,你會發(fā)現(xiàn)Demo示意圖還有個小細節(jié)那就是圖片列表的圖片都是圓角的,那么今天就來說說如何快速生成圓角或者圓形圖片。

在今年I/O大會之前,如果要實現(xiàn)圓角或者圓形圖片可以自定義View,比如之前的博文 《Android 自定義UI View - 03 圓形圖片控件》 或者通過一些第三方庫來實現(xiàn),比如下面這個:

  • RoundedImageView by vinc3m1

但是在I/O大會之后,Google發(fā)布了新的Support lib,其中有一個是 RoundedBitmapDrawable 類,通過這個類可以很容易實現(xiàn)圓角和圓形圖片。

可以直接在上一個工程的基礎上修改部分代碼實現(xiàn),具體實現(xiàn)步驟如下:

1、首先需要添加support-v4依賴

在build.gralde的dependencies中添加下面代碼:

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、創(chuàng)建RoundedBitmapDrawable對象

生成圓角圖片:

Bitmap src = BitmapFactory.decodeResource(getResources(), imageId); //獲取Bitmap圖片RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), src); //創(chuàng)建RoundedBitmapDrawable對象roundedBitmapDrawable.setCornerRadius( 100 ); //設置圓角半徑(根據(jù)實際需求)roundedBitmapDrawable.setAntiAlias( true ); //設置反走樣image.setImageDrawable(roundedBitmapDrawable); //顯示圓角圖片

生成圓角圖片只需要根據(jù)圖片大小設置合理的圓角半徑即可,效果如下:

生成圓形圖片
由于 RoundedBitmapDrawable 類沒有直接提供生成圓形圖片的方法,所以生成圓形圖片首先需要對原始圖片進行裁剪,將圖片裁剪成正方形,最后再生成圓形圖片,具體實現(xiàn)如下:

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

總結

以上是生活随笔為你收集整理的使用RoundedBitmapDrawable快速生成圆角和圆形图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。