【问题标题】:Image cropping from UIImageView从 UIImageView 裁剪图像
【发布时间】: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


【解决方案1】:

您确定需要两个比率吗?如果您希望图像具有正确的比例,则应仅使用一种比例。

如果您需要填充一个矩形(即使 UIImageView 为您完成),那么首先计算 x 轴上的比率。使用这个比率计算缩放高度,如果它小于您需要覆盖的高度,则计算 y 轴上的比率。

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

【讨论】:

  • 是的,你很好。对于宽度和高度,不需要两个比率。但是对于 x 和 y 位置,我仍然需要两个比率。 x,y 位置乘法有一些位置偏移。
  • 是的 - 没错。但是您的图像具有预期的大小和比例,不是吗?顺便说一句,我宁愿使用图像的中心作为参考,而不是左上角。如果您使用不同的比率来缩放偏移量和尺寸,我不确定它是否可以工作..
  • 是的,谢谢,中心是一种以固定间隔添加的左上角。我认为它会是一样的。因为我的矩形是正方形的。
  • 但您的源图像不是。我不认为中心不是“一种……”。是中心。不管长方形还是正方形。那么也许左上角是一种以固定间隔添加的中心:D!笑话appart,也许您可​​以尝试简单地计算您的正方形大小,将其放在原始图像的中心,然后进行裁剪。
  • 你怎么这么好。是的,源图像不是。现在没有偏移量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 2013-04-02
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多