ios - 从 UIImageView 裁剪图像

标签 ios objective-c iphone image 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 上显示的区域。但仍然有一点区域偏移和失真。在这种情况下,最好的裁剪方式是什么? 我的代码如下所示

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

}

最佳答案

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

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

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

关于ios - 从 UIImageView 裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541032/

相关文章:

ios - 发现启动 URL (iOS)

ios - 如何使用 Swift3 在​​ FIrebase 中查询/检查特定的键/值对

ios - 添加子 Controller 或 Present 时奇怪的情况在 Storyboard中的 Mapview 上崩溃(添加了示例代码)

ios - 从另一个 Storyboard 以编程方式加载 UISplitViewController

ios - 扩展或自定义 cocoapods 的正确方法

iphone - iOS 5 Segue 在第一次执行后不工作

iphone - iOS - FMDB 数据库插入

ios - UITextField 输入不工作

iphone - 如何在没有 Storyboard 的情况下使用 Core Data?

iphone - 你的第二个 iOS 应用 : Edit one object in two different views