簡體   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