android 图片 圆角

来源:互联网 发布:吉林大学ei数据库 编辑:程序博客网 时间:2024/05/02 17:03
  1. public class PhotoTestActivity extends Activity {
  2.     /** Called when the activity is first created. */
  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.main);
  7.         ImageView image = (ImageView)findViewById(R.id.image);
  8.         Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.test);
  9.         image.setImageBitmap(createFramedPhoto(500,400,photo,50));
  10.     }

  11.     /**
  12.      *
  13.      * @param x 图像的宽度
  14.      * @param y 图像的高度
  15.      * @param image 源图片
  16.      * @param outerRadiusRat 圆角的大小
  17.      * @return 圆角图片
  18.      */
  19.     Bitmap createFramedPhoto(int x, int y, Bitmap image, float outerRadiusRat) {
  20.         //根据源文件新建一个darwable对象
  21.         Drawable imageDrawable = new BitmapDrawable(image);

  22.         // 新建一个新的输出图片
  23.         Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
  24.         Canvas canvas = new Canvas(output);

  25.         // 新建一个矩形
  26.         RectF outerRect = new RectF(0, 0, x, y);

  27.         // 产生一个红色的圆角矩形
  28.         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  29.         paint.setColor(Color.RED);
  30.         canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);

  31.         // 将源图片绘制到这个圆角矩形上
  32.         paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
  33.         imageDrawable.setBounds(0, 0, x, y);
  34.         canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
  35.         imageDrawable.draw(canvas);
  36.         canvas.restore();

  37.         return output;
  38.     }
  39. }








public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {int x = bitmap.getWidth();int y = bitmap.getHeight();float[] mOuter = new float[] { roundPx, roundPx, roundPx, roundPx,roundPx, roundPx, roundPx, roundPx };// 根据源文件新建一个darwable对象Drawable imageDrawable = new BitmapDrawable(bitmap);// 新建一个新的输出图片Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(output);// 新建一个矩形RectF outerRect = new RectF(0, 0, x, y);Path mPath = new Path();// 创建一个圆角矩形路径mPath.addRoundRect(outerRect, mOuter, Path.Direction.CW);// 画出一个红色的圆角矩形Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);paint.setColor(Color.RED);paint.setAntiAlias(true);canvas.drawPath(mPath, paint);// 设置绘图两层交汇时的模式paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置绘图区域(在那个区域内绘图)imageDrawable.setBounds(0, 0, x, y);// 将用于绘制图片的图层压入图层栈canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);// 将源图片绘制到这个圆角矩形上imageDrawable.draw(canvas);// 将图片图层退出栈并将图像绘制到矩形的那一层canvas.restore();return output;}


原创粉丝点击