当前位置: 代码迷 >> Android >> 一行学android之设置资源图片为圆角图片 (28)
  详细解决方案

一行学android之设置资源图片为圆角图片 (28)

热度:91   发布时间:2016-04-28 02:00:49.0
一起学android之设置资源图片为圆角图片 (28)

效果图:







参看以下代码:

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 情绪控_

  相关解决方案