【发布时间】:2016-02-06 01:54:31
【问题描述】:
我有一个大小为 (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 所示尽可能接近地裁剪该区域。但仍然有一点区域偏移和失真。在这种情况下,最好的种植方式是什么?
我的代码如下所示
- (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 =@"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]);
}
【问题讨论】:
-
尝试在计算中使用 floor(),以避免部分像素对齐,尤其是对于原点。
-
No floor() 去掉小数点,裁剪区域错误较多。
标签: ios objective-c iphone image uiimageview