项目需要,要显示用户的二维码,但是服务器返回的是一整张图片,直接放在界面上有点丑,需要截出来中间的码部分,效果如图
关键的方法是:
public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) {
return createBitmap(source, x, y, width, height, null, false);
}
参数说明:
Bitmap source:要处理的原始位图
int x ,y:起始位置坐标
int width:要截的图的宽度
int height:要截的图的宽度
返回值:返回处理后的Bitmap
拿到bitmap可以做相关操作,最后贴一下代码,方便以后复制粘贴,哈哈
findViewById(R.id.btnCommit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//使用Bitmap获取保存在drawable中的图片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.spread);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, (int) (width * 0.2), (int) (height * 0.07),
(int) (width * 0.60), (int) (height * 0.58));
if (bitmap != null & !bitmap.isRecycled()){
bitmap.recycle();//销毁原图片
bitmap = null;
}
iv_new.setImageBitmap(bitmap1);
}
});