圓角矩形圖片在蘋果的產品中很流行,相比於普通的矩形,很多人都喜歡圓角矩形的圖片,因為它避開了直角的生硬,帶來更好的用戶體驗,下面是幾個設計的例子:
下面在Android中實現將普通的矩形圖片繪制成圓角矩形。首先看最終效果:
代碼清單:
- package com.example.phototest;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Path;
- import android.graphics.PorterDuffXfermode;
- import android.graphics.PorterDuff;
- import android.graphics.RectF;
- import android.graphics.drawable.BitmapDrawable;
- import android.graphics.drawable.Drawable;
- import android.view.Menu;
- import android.widget.ImageView;
-
- public class MainActivity extends Activity {
-
- private ImageView myImageView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- myImageView=(ImageView)findViewById(R.id.imageView1);
- Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.photo1);
- myImageView.setImageBitmap(createFramedPhoto(500,400,photo,20));
- //myImageView.setImageBitmap(createStarPhoto(500,400,photo));
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- private 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);
-
-
- // 將源圖片繪制到這個圓角矩形上
- //詳解見http://lipeng88213.iteye.com/blog/1189452
- 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;
- }
- }