从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]); 

} 
+0

尝试在您的计算中使用floor(),以避免部分像素对齐,特别是对于原点。 – Avi

+0

没有floor()删除小数点并且在裁剪区域中出现更多错误。 – batuman

您确定需要两个比率吗?如果你希望你的图像具有合适的比例,你只能使用一个比例。

如果你需要填充一个矩形(即使UIImageView为你做),然后首先计算x轴上的比例。使用此比率计算缩放高度(如果它小于需要覆盖的高度),然后计算y轴上的比率。

最后,刚刚计算的比例是用来缩放图像的比例。

+0

是的,你很好。对于宽度和高度,不需要两个比例。但是对于x和y位置,我仍然需要两个比率。 x,y位置乘法有一些位置偏移。 – batuman

+0

是的 - 没错。但是,那么你的形象有预期的规模和比例,不是吗? 顺便说一句,我宁愿使用图像的中心作为参考比左上角。 如果您使用不同比例来缩放您的偏移量和尺寸,我不确定它可以工作。 – Moose

+0

是的,谢谢,中心是一种左上角添加了固定间隔。我认为这将是相同的。因为我的矩形是方形的。 – batuman