如何修复Canvas/Bitmap旋转后边缘被裁切的问题?
解决Bitmap旋转后被裁切的问题
嘿,这个坑我之前踩过!你遇到的裁切问题,本质是旋转后的图像实际需要的画布尺寸比原来的合并图尺寸要大——非直角(90/180/270度)旋转会让图像的外接矩形变大,超出原画布的范围,自然就被切掉边缘了。
解决思路
核心是先算出旋转后图像的实际占用尺寸,再创建足够大的新画布,最后把旋转后的图像居中绘制到新画布上。
具体代码实现
替换你原来的旋转代码,改成下面这样:
// 1. 先拿到合并后的Bitmap的原尺寸 int mergedWidth = bitmapMerged.getWidth(); int mergedHeight = bitmapMerged.getHeight(); // 2. 创建旋转矩阵,先设置旋转角度 Matrix matrix = new Matrix(); matrix.postRotate(10); // 你的旋转角度 // 3. 计算旋转后图像的外接矩形大小 RectF rotatedBounds = new RectF(0, 0, mergedWidth, mergedHeight); matrix.mapRect(rotatedBounds); // 4. 根据计算出的边界,创建足够大的新Bitmap int newWidth = Math.round(rotatedBounds.width()); int newHeight = Math.round(rotatedBounds.height()); Bitmap rotatedBitmap = Bitmap.createBitmap(newWidth, newHeight, bitmapMerged.getConfig()); // 5. 调整矩阵,让旋转后的图像居中显示在新画布上(避免偏移) matrix.postTranslate((newWidth - mergedWidth) / 2f, (newHeight - mergedHeight) / 2f); // 6. 绘制旋转后的图像 Canvas rotatedCanvas = new Canvas(rotatedBitmap); rotatedCanvas.drawBitmap(bitmapMerged, matrix, null);
为什么原来的代码不行?
你之前直接给canvasMerged设置矩阵,但这个Canvas的尺寸还是合并后的原图大小。旋转后图像的边缘已经超出了这个画布的范围,超出部分就被自动裁切了。而上面的方法是先算出旋转后需要的画布大小,再让图像居中绘制,自然就不会裁切了。
内容的提问来源于stack exchange,提问作者Joselito Macablo
相关产品推荐
相关产品推荐

