RoundedBitmapDrawable生成圓角圖片

 

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

動態spa

生成圓形圖片
因爲RoundedBitmapDrawable類沒有直接提供生成圓形圖片的方法,因此生成圓形圖片首先須要對原始圖片進行裁剪,將圖片裁剪成正方形,最後再生成圓形圖片,具體實現以下:code

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);
相關文章
相關標籤/搜索