这里介绍一个主要的方法,也是从网上找的,在此整理出来。。。以备不时之需
/** * 将图片设置为圆角 */ public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) { 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 = pixels; 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; }
当我们需要圆角的时候,调用这个方法,第一个参数是传入需要转化成圆角的图片,第二个参数是圆角的度数,数值越大,圆角越大
下面兴趣个例子,我有一个LinearLayout,我想把它的背景图片设置成圆角
布局文件main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> </LinearLayout>
mInflater = LayoutInflater.from(this); Drawable drawable = getResources().getDrawable(R.drawable.icon); BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); View view = mInflater.inflate( R.layout.share_xiaohua_revert_lv_item_top, null); ImageView mImageView = (ImageView) view .findViewById(R.id.lv_xiaohua_image); mImageView.setImageBitmap(toRoundCorner(bitmap, 30));