Android——自定义组件与游戏开发(三)bitmap适配
问题描述
Canvas.drawBitmap(Bitmap bitmap,Rect srcRect ,Rect dstRect , paint)
绘制图片比原图片尺寸大
因此需要
1. 对Bitmap缩放或扩大
2. 根据系统尺寸对Bitmap缩放扩大
1.
private Bitmap changeBitmapSize() {undefined Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); int width = bitmap.getWidth(); int height = bitmap.getHeight(); Log.e("width","width:"+width); Log.e("height","height:"+height); //设置想要的大小 int newWidth=30; int newHeight=30; //计算压缩的比率 float scaleWidth=((float)newWidth)/width; float scaleHeight=((float)newHeight)/height; //获取想要缩放的matrix Matrix matrix = new Matrix(); matrix.postScale(scaleWidth,scaleHeight); //获取新的bitmap bitmap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true); bitmap.getWidth(); bitmap.getHeight(); Log.e("newWidth","newWidth"+bitmap.getWidth()); Log.e("newHeight","newHeight"+bitmap.getHeight()); return bitmap; }
2.
/** * 起因是测试在测试过程中发现需要裁剪的图片看不到,但是还能继续裁剪。 * 所以就检查代码,发现了bitmap的width和Height有3000多。 * 然后试了下把图片改成300*300的就显示正常, * 所以我们需要让图片根据大小不同,机器不同而改变图片的宽高 */
//设置分辨率 //1.获取系统分辨率 Resources resources = this.getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); //2.获取图片分辨率 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;// 这个方式不会在内存创建一张图片, Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); //此时返回的bitmap为null,但是option会保留一部分参数 //3.确定分辨率 int height = options.outHeight; int width = options.outWidth; if(options.outHeight>dm.heightPixels*1.5f){//当图片大小比屏幕大1.5倍的时候,直接以系统高度为高度 height = dm.heightPixels; } if (options.outWidth>dm.widthPixels*1.5f){ width = dm.widthPixels; } options.inJustDecodeBounds = false;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?