gpt4 book ai didi

objective-c - 如何用颜色填充 imageview 中的空白(未被图像覆盖)?

转载 作者:行者123 更新时间:2023-11-28 20:43:15 24 4
gpt4 key购买 nike

我想创建一个固定大小的图像,例如612 x 612。我正在使用图像选择器从我的 iPhone 中选择照片。所以为了保证所有的照片都符合612 x 612的尺寸而不变形,我用下面的方法重新缩放照片,使它们符合612 x 612的尺寸。但是结果,空白可能会在最终图像中创建。 (见下面的例子)

我正在使用以下代码来缩放我的图像(固定大小为 612 x 612)

//Scale the image to fit to imageview
UIImage *image = [self scaleImage:img toRectSize:CGRectMake(0, 0, 612, 612)];


//Method to scale image
- (UIImage *)scaleImage:(UIImage *)img toRectSize:(CGRect)screenRect
{
UIGraphicsBeginImageContext(screenRect.size);
float hfactor = img.size.width / screenRect.size.width;
float vfactor = img.size.height / screenRect.size.height;

float factor = MAX(hfactor, vfactor);

float newWidth = img.size.width / factor;
float newHeight = img.size.height / factor;

float leftOffset = (screenRect.size.width - newWidth) / 2;
float topOffset = (screenRect.size.height - newHeight) / 2;

CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight);
[img drawInRect:newRect blendMode:kCGBlendModePlusDarker alpha:1];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return newImage;
}

如前所述,由于图像有时不是完整的正方形,我得到的结果如下所示:

enter image description here

我怎样才能感觉到黑色图像中的空白区域?

最佳答案

一种方法是将 UIImageViewbackgroundColor 设置为 blackColor

另一种方法是在缩放图像时用 blackColor 填充矩形。

- (UIImage *)scaleImage:(UIImage *)img toRectSize:(CGRect)screenRect {

...
CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight);

// Fill the original rect with black color
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, screenRect);

[img drawInRect:newRect blendMode:kCGBlendModeNormal alpha:1];
...
}

请注意,drawInRect:blendMode:alpha: 方法中的 blendMode 设置为 kCGBlendModeNormal。如果你设置一些其他的混合模式,你会得到不想要的结果。例如,如果将混合模式设置为 kCGBlendModePlusDarker 并用 blackColor 填充矩形,则整个图像将变为黑色。

关于objective-c - 如何用颜色填充 imageview 中的空白(未被图像覆盖)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7482894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com