gpt4 book ai didi

ios - Swift - 为 CGrect 添加颜色

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:13 26 4
gpt4 key购买 nike

我目前正在向图像添加一个矩形,以防它不是正方形“填充”剩余空间,使其成为正方形。这个想法是,这是一种廉价的方法(就“强制”图像进行平方所需的时间而言)。

如您在附图中所见,我生成的正方形没有颜色,这可能会使用户感到困惑。这就是为什么我想为我生成的 CGRect 添加颜色。问题是我还没有找到任何方法来做到这一点。任何有关如何为生成的正方形着色的建议,将不胜感激。

enter image description here

enter image description here

我必须执行此操作的当前代码如下:

func forceSquaredImage(image: UIImage) -> UIImage{
let maxDimension = max(image.size.height, image.size.width)

var newImage : UIImage = image

if(image.size.height > image.size.width){

UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);

image.drawInRect(CGRectMake(image.size.height/2-image.size.width/2, 0, image.size.width, image.size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

}else if(image.size.height < image.size.width){

UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);
image.drawInRect(CGRectMake(0, image.size.width/2-image.size.height/2, image.size.width, image.size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage

}

return newImage

}

期望的结果应该是这样的(在这种情况下,红色只是一个例子):

enter image description here

最佳答案

在绘制图像之前填充背景颜色:

func forceSquaredImage(image: UIImage) -> UIImage{
let maxDimension = max(image.size.height, image.size.width)

var newImage : UIImage = image
UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);
UIColor.redColor().set()
UIBezierPath(rect: CGRect(x:0, y: 0, width:maxDimension, height:maxDimension)).fill()
if(image.size.height > image.size.width) {
image.drawInRect(CGRectMake(image.size.height/2-image.size.width/2, 0, image.size.width, image.size.height))
}
else if (image.size.height < image.size.width) {
image.drawInRect(CGRectMake(0, image.size.width/2-image.size.height/2, image.size.width, image.size.height))
}
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage
}

关于ios - Swift - 为 CGrect 添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789179/

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