在最近的機頂盒媒體中心開發中,遇到這樣一個需求
需要將每張圖片展示為正方形,并且擁有圓角。所以先將圖片裁剪為正方形,再畫出圓角
布局:
<ImageView
android:id="@+id/iv"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp"
android:scaleType="centerCrop"/>
android:id="@+id/btn"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#16e2c7"
android:text="show"/>
將bitmap裁剪為正方形
public staticBitmapgetRoundCornerImage(Bitmap bitmap, intmRadius, ImageView imageView) {
intwith = imageView.getWidth();
intheight = imageView.getHeight();
intbwith = bitmap.getWidth();
intbheight = bitmap.getHeight();
intsw = 0;
intsh = 0;
intew = 0;
inteh = 0;
Bitmap roundConcerImage = null;
if (bheight == bwith) {
roundConcerImage = bitmap;
} else {
if (bheight > bwith) {
sw = 0;
//裁剪圖片中間部位
sh = (bheight - bwith) / 2;
ew = bwith;
eh = bwith;
} else {
sh = 0;
sw = (bwith - bheight) / 2;
ew = bheight;
eh = bheight;
}
//創建一個正方形的Bitmap
roundConcerImage = Bitmap.createBitmap(bitmap, sw, sh, ew, eh);
}
roundConcerImage = Bitmap.createScaledBitmap(roundConcerImage, with, height, true);
//畫出圓角
returncreateRoundConerImage(roundConcerImage, mRadius);
}
private staticBitmapcreateRoundConerImage(Bitmap source, intmRadius) {
finalPaint paint = newPaint();
// 去鋸齒
paint.setAntiAlias(true);
// 創建一個和原始圖片一樣大小位圖
Bitmap target = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = newCanvas(target);
// 創建一個和傳入圖片一樣大小的矩形
RectF rect = newRectF(0, 0, source.getWidth(), source.getHeight());
// 畫一個和原始圖片一樣大小的圓角矩形
canvas.drawRoundRect(rect, mRadius, mRadius, paint);
// 設置相交模式 取兩者相交的部位
paint.setXfermode(newPorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// 把圖片畫到矩形去
canvas.drawBitmap(source, 0, 0, paint);
returntarget;
}
在onCreate中調用方法
iv= (ImageView) findViewById(R.id.iv);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View v) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.img);
Bitmap roundCornerImage =getRoundCornerImage(bitmap,7,iv);
iv.setImageBitmap(roundCornerImage);
}
});
實際效果