Android Bitmap的優化

這裏列出兩種常用的Bitmap的優化 :

1. 給Bitmap設置圓角效果

下面的代碼當我們需要圓角的時候,調用這個方法,第一個參數是傳入需要轉化成圓角的圖片,第二個參數是圓角的度數,數值越大,圓角越大

public final static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
}

2. 當圖片過大,給Bitmap進行二次採樣,壓縮圖片

    第一個參數是圖片byte資源,第二第三個參數分別是你要壓縮出來圖片的高和寬
    

// 通過Options對咱們圖片加載進行控制
public static Bitmap sample(byte[] source,int requreHeight,int requreWidth){
// 實例化一個Options
BitmapFactory.Options options = new BitmapFactory.Options();
// 設置爲true,decode之後不會生成bitmap,它是對bitmap的基本信息進行獲取,信息存在options中
options.inJustDecodeBounds = true;
// 爲options進行賦值
BitmapFactory.decodeByteArray(source,0,source.length,options);
// bitmap的高
int outHeight = options.outHeight;
// bitmap的寬
int outWidth = options.outWidth;
// 假如你需要的寬度是400,採樣比例應該怎麼算
int sampleWidth = outWidth / requreWidth;
//  計算高度採樣比率
int sampleHeight = outHeight / requreHeight;
// 獲取最大的壓縮比率
int sample = Math.max(sampleHeight,sampleWidth);
// 設置壓縮比率
options.inSampleSize = sample;
// 不要只讀基本信息,邊緣了。
options.inJustDecodeBounds = false;

    return BitmapFactory.decodeByteArray(source,0,source.length,options());

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章