【AndroidSupport】RoundedBitmapDrawable 建立一個圓角圖片

#【AndroidSupport】RoundedBitmapDrawable 建立一個圓角圖片android

##簡介 RoundedBitmapDrawable 是 android.support.v4.graphics.drawable 裏面的一個類,用來建立簡單的圓角圖片。 若是隻是簡單的圓角展現,好比展現一個圓角頭像,這個類徹底能夠勝任。git

##簡單使用github

  1. 獲取 RoundedBitmapDrawable。RoundedBitmapDrawable 是一個抽象類,沒法直接獲取。因此提供了 RoundedBitmapDrawableFactory 來操做:code

    RoundedBitmapDrawableFactory的靜態簽名:圖片

    static RoundedBitmapDrawable	create(Resources res, InputStream is)
     static RoundedBitmapDrawable	create(Resources res, String filepath)
     static RoundedBitmapDrawable	create(Resources res, Bitmap bitmap)

    沒有提供直接從 resId 獲取的方法,可是是同樣的:get

    RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.xxx));
  2. 設置屬性。幾個重要的屬性:it

    1. cornerRadius:圓角半徑
    2. alpha:透明度

    若是想獲得一個圓形,那麼能夠直接調用 RoundedBitmapDrawable#setCircular(true),原理

    不過這樣須要注意點是,若是原始的圖形不是圓形,那麼圖形會變形。渲染

    固然,結果還與 scaleType 有關,這裏有點複雜,暫無需關心。因此,若是你想要一個圓形,你就給一個正方形。file

    不要同時設置 cornerRadius 和 setCircular(true),由於二者是衝突的。

  3. 設置 Drawable。 ImageView#setImageDrawable(roundedBitmapDrawable);

##原理

RoundedBitmapDrawable 內部使用 BitmapShader 來處理圖形渲染,無他。

#第三方開源控件

RoundedBitmapDrawable 的侷限性仍是比較大,若是想要實現一寫些自由度更大的圓角,邊框等等,能夠考慮使用第三方空間,好比:

CircularImageView RoundedImageView

###Android分享 Q羣:315658668

相關文章
相關標籤/搜索