繁体   English   中英

如何将黑色区域添加到UIImage iOS

[英]How to add black color area to UIImage ios

我正在处理图像。 我有一个裁剪功能,该功能仅允许以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中崩溃。

还有其他方法可以在图像上添加黑色区域而不会导致内存泄漏吗?

希望您理解问题。

提前致谢。

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

// 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM