Android之设置资源图片为圆角图片

效果图:

 

 

 

 

 

参看以下代码:

 

public class MainActivity extends Activity {
	private ImageView imageView1;
	private ImageView imageView2;
	Bitmap mBitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image);
		initView();
	
	}

	private void initView(){
		imageView1=(ImageView)findViewById(R.id.imageView1);
		imageView2=(ImageView)findViewById(R.id.imageView2);
		//读取资源图片
		mBitmap=readBitMap();
		//对资源图片进行缩放
		Bitmap bitmap=zoomBitmap(mBitmap, mBitmap.getWidth()/2, mBitmap.getHeight()/2);
		//设置圆角图片
		imageView2.setImageBitmap(setRoundedCorner(bitmap,20f));
	}
	
	
	/**
	 * 读取资源图片
	 * @return 
	 */
	private Bitmap readBitMap(){
		BitmapFactory.Options opt=new BitmapFactory.Options();
		/*
		 * 设置让解码器以最佳方式解码
		 */
		opt.inPreferredConfig=Bitmap.Config.RGB_565;
		//下面两个字段需要组合使用
		opt.inPurgeable=true;
		opt.inInputShareable=true;
		/*
		 * 获取资源图片
		 */
		InputStream is=this.getResources().openRawResource(R.drawable.mei);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	
	/**
	 * 缩放图片
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public  Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		/*
		 * 通过Matrix类的postScale方法进行缩放
		 */
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		return newbmp;
	}
	
	/**
	 * 设置图片为圆角
	 * @param bitmap
	 * @param roundPx  圆角角度
	 * @return
	 */
	public  Bitmap setRoundedCorner(Bitmap bitmap, float roundPx) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		/*
		 * 椭圆形
		 */
		final RectF rectF = new RectF(rect);
		/*
		 * 去锯齿
		 */
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);

		/*
		 * 绘制圆角矩形
		 */
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		/*
		 * 设置两个图形相交
		 */
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}
	
}

 

 

 

 

 

转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/44314043 情绪控_

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值