Android圓角圖片彙總

今天來對圖片的圓角處理作一個簡單小結,不少app裏面都有圓角效果,根據不一樣的場景能夠採用不一樣的方案,目前來講有三種方案是比較經常使用的html

方案一 .9.pngjava

應用場景:1.目標圖片已知;2.針對佈局背景;android

實現:canvas

.9.png是最簡單的方法,只須要用draw9patch準備好相應的.9圖,設置爲控件的背景便可.app

參考:http://developer.android.com/tools/help/draw9patch.html佈局

方案二 剪裁Bitmapui

應用場景:1.圖片事先沒法預知;2.圖片不是很是大 + 方案一場景spa

實現:htm

這裏的剪裁指的是根據原圖咱們本身生成一張新的bitmap,這個時候指定圖片的目標區域爲一個圓角局域。這種作法有一點須要生成一個新的bitmap,因此會消耗至少2倍的圖片內存,圖片

下面分析一下代碼的含義:

a.首先建立一個指定高寬的bitmap,做爲輸出的內容,

b.而後建立一個相同大小的矩形,利用畫布繪製時指定圓角角度,這樣畫布上就有了一個圓角矩形。

c.最後就是設置畫筆的剪裁方式爲Mode.SRC_IN,將原圖疊加到畫布上,

這樣輸出的bitmap就是原圖在矩形局域內的內容。

  public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
        bitmap.getHeight(), 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 = 12;
 
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
 
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
 
    return output;
  }

參考:http://ruibm.com/?p=184

方案三 直接繪製圓角bitmap

應用場景:同方案二

這個寫法是android team的成員寫出來的,特色就是不用不須要額外在建立一個圖片,這裏把原圖構形成了一個BitmapShader,而後就能夠用畫布直接畫出圓角的內容

BitmapShader shader;shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Paint paint = new Paint();

paint.setAntiAlias(true);

paint.setShader(shader);

RectF rect = new RectF(0.0f, 0.0f, width, height);

// rect contains the bounds of the shape

// radius is the radius in pixels of the rounded corners

// paint contains the shader that will texture the shape

canvas.drawRoundRect(rect, radius, radius, paint);

參考:http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/

相關文章
相關標籤/搜索