从UIImageView中裁剪图像
问题描述:
我有一个尺寸为(0,0,414,471)的UIImageView
。大小为(0,0,1236,1242)的图像在UIImageView
中以UIViewContentModeScaleAspectFit
模式显示。所以图像很好地显示。然后我在图像上画出一个矩形(0,0,100,100),并且我喜欢裁剪它。尽管UIImageView
上覆盖了(100,100)的矩形,但在实际图像尺寸上,(100,100)不包含UIImageView
上显示的尺寸。所以我制作xratio(实际宽度/显示宽度)和yratio(实际高度/显示高度),然后将矩形大小乘以矩形的所有x,y,宽度和高度。这种方法看起来像我可以尽可能地接近区域,如UIImageView
所示。但仍有一些区域偏移和失真。在这种情况下裁剪的最佳方式是什么? 我的代码如下所示从UIImageView中裁剪图像
- (void)saveCroppedImage:(UIImage *)image withcroppedRectangle:(CGRect)clippedRect
{
float xratio = image.size.width/displayWidth;
float yratio = image.size.height/displayHeight;
// Crop logic
clippedRect.origin.x *= xratio;
clippedRect.origin.y *= yratio;
clippedRect.size.width *= xratio;
clippedRect.size.height *= yratio;
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
UIImage * croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
NSString *imageName [email protected]"Documents/";
imageName = [imageName stringByAppendingString:[CurrentToddlerProfile getUserID]];
imageName = [imageName stringByAppendingString:@".png"];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:imageName];
// Write image to PNG
[UIImagePNGRepresentation(croppedImage) writeToFile:pngPath atomically:YES];
// Create file manager
// NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSError *error;
// // Point to Document directory
// NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
// // Write out the contents of home directory to console
// NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}
答
您确定需要两个比率吗?如果你希望你的图像具有合适的比例,你只能使用一个比例。
如果你需要填充一个矩形(即使UIImageView为你做),然后首先计算x轴上的比例。使用此比率计算缩放高度(如果它小于需要覆盖的高度),然后计算y轴上的比率。
最后,刚刚计算的比例是用来缩放图像的比例。
尝试在您的计算中使用floor(),以避免部分像素对齐,特别是对于原点。 – Avi
没有floor()删除小数点并且在裁剪区域中出现更多错误。 – batuman