转自:http://blog.chinaunix.net/uid-20771867-id-3260250.html
圆角矩形图片在苹果的产品中很流行,相比于普通的矩形,很多人都喜欢圆角矩形的图片,下面在Android中实现将普通的矩形图片绘制成圆角矩形。
先来看一下普通矩形图片的显示,代码很简单,从resource中将图片取出来直接拿来用:
点击(此处)折叠或打开
- 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(photo);
- }
- }
四个角是直角的图片是不是看起来不那么舒服呢?下面将直角转换为圆角:
点击(此处)折叠或打开
- 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;
- }
- }
方法的原理就是先创建出一个圆角矩形的图片,然后将我们原来的图片作为上面的一层覆盖在这个圆角矩形上,并且使用该圆角图片的形状。ok,看看结果吧,是不是看起来好多了?