- public class PhotoTestActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ImageView image = (ImageView)findViewById(R.id.image);
- Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.test);
- image.setImageBitmap(createFramedPhoto(500,400,photo,50));
- }
-
- /**
- *
- * @param x 图像的宽度
- * @param y 图像的高度
- * @param image 源图片
- * @param outerRadiusRat 圆角的大小
- * @return 圆角图片
- */
- Bitmap createFramedPhoto(int x, int y, Bitmap image, float outerRadiusRat) {
- //根据源文件新建一个darwable对象
- Drawable imageDrawable = new BitmapDrawable(image);
-
- // 新建一个新的输出图片
- Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
- Canvas canvas = new Canvas(output);
-
- // 新建一个矩形
- RectF outerRect = new RectF(0, 0, x, y);
-
- // 产生一个红色的圆角矩形
- Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
- paint.setColor(Color.RED);
- canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, 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;
- }
- }
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;
}