今天來對圖片的圓角處理做一個簡單小結,很多app里面都有圓角效果,根據不同的場景可以采用不同的方案,目前來說有三種方案是比較常用的
方案一 .9.png
應用場景:1.目標圖片已知;2.針對布局背景;
實現:
.9.png是最簡單的方法,只需要用draw9patch准備好相應的.9圖,設置為控件的背景即可.
參考:http://developer.android.com/tools/help/draw9patch.html
方案二 剪裁Bitmap
應用場景:1.圖片事先無法預知;2.圖片不是非常大 + 方案一場景
實現:
這里的剪裁指的是根據原圖我們自己生成一張新的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; }
方案三 直接繪制圓角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/