日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

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

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

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

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

  • RoundedImageView by vinc3m1

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

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

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、創建RoundedBitmapDrawable對象

生成圓角圖片:

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

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

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

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快速生成圆角和圆形图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。