【问题标题】:How to add black color area to UIImage ios如何将黑色区域添加到 UIImage ios
【发布时间】:2020-01-17 07:40:52
【问题描述】:

我正在处理图像。我有一个裁剪功能,它只允许以 2:1 的比例(宽:高比)进行裁剪。因此,如果图像是其他比例,用户可以缩小图像并将图像放在裁剪窗口内,但我想在图像的一侧添加黑色区域,以便生成的图像始终保持 2:1 的比例。

请看截图

这是我正在使用的代码:

#Check the ratio
#Get the resultant size ie. resultant width and height

//crashes here
UIGraphicsBeginImageContextWithOptions(CGSizeMake(newImageWidth, newImageHeight), YES, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
CGPoint origin = CGPointMake((newImageWidth - image.size.width) / 2.0f, (newImageHeight - image.size.height) / 2.0f);
[image drawAtPoint:origin];
UIGraphicsPopContext();

此代码在 iOS 应用程序中运行良好,但当我在应用程序扩展中使用此代码时,由于内存泄漏而崩溃。它在 UIGraphicsBeginImageContextWithOptions 中崩溃。

有没有其他方法可以在图像中添加黑色区域而不会发生内存泄漏?

希望你能理解问题。

提前致谢。

【问题讨论】:

  • -[UIColor setFill] + UIRectFill
  • @Cy-4AH 你能详细说明你的答案吗?
  • 什么不清楚?设置填充黑色并填充您需要的矩形。

标签: ios objective-c uiimage ios-app-extension


【解决方案1】:

UIImageView 非常擅长切面拟合、填充、缩放等操作。您可以让一个人为您完成计算和 bitblit 工作,然后使用图像上下文渲染结果。未经测试,但像这样......

// answer a new UIImage that has 2:1 aspect and fits a given input image
// for now, scale it clumsily and extra small to prove or rule out memory issue
+ (UIImage *)aspectFit:(UIImage *)image {
    CGRect frame = CGRectMake(0, 0, 200, 100);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.backgroundColor = [UIColor blackColor];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;

    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, YES, 0.0);
    [imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

通过在任一维度上设置最大值并缩放到该值,可以使缩放计算更加复杂。选择要限制的值是应用程序需要的问题(通常,当前的显示大小很有帮助)。计算很简单...

// calculate a frame smaller than the starting image to scale to
CGFloat maxHeight = 600; // or an fn() of display, up to the app needs
CGSize size = image.size;
CGFloat scale = MAX(size.height, maxHeight) / size.height;
CGRect frame = CGRectMake(0, 0, size.width*scale, size.height*scale);

【讨论】:

  • 在您的回答中,您仍在使用 UIGraphicsBeginImageContextWithOptions,这是应用程序崩溃的地方。对于大尺寸的图像,它仍然会崩溃。
  • 请发布崩溃。 “大”是什么意思?在对过大的图像进行任何操作之前,您可能需要缩减样本。
  • 扩展程序崩溃了,我没有得到任何日志。当我尝试裁剪实况照片时会出现此问题。但并非所有 Live Photos 都发生崩溃,只是随机 Live Photos。我怀疑这与图像的大小有关。
  • 缩小比例怎么样?
  • 你能推荐一种缩小比例的方法
猜你喜欢
  • 2020-10-20
  • 2012-12-20
  • 2013-04-21
  • 2013-04-06
  • 2015-08-29
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多