一起学android之设置资源图片为圆角图片 (28)
16lz
2021-01-23
效果图:
参看以下代码:
public class MainActivity extends Activity {private ImageView imageView1;private ImageView imageView2;Bitmap mBitmap;@Overrideprotected 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情绪控_
更多相关文章
- Android异步加载图片并缓存到内存和SD卡上
- Android中ImageSwitcher结合Gallery展示SD卡中的资源图片
- ImageView 设置图片
- 阅读《Android 从入门到精通》(24)——切换图片
- android 删除SD卡或者手机的缓存图片和目录
- android 视频图片混合轮播实现
- android用ImageView显示网络图片