gpt4 book ai didi

ios - 如何在边缘为白色的正方形内绘制完整的 UIImage

转载 作者:行者123 更新时间:2023-11-28 18:55:47 25 4
gpt4 key购买 nike

您好,就像我在标题中所说的那样,我正在尝试在与 UIImage 的最大尺寸相匹配的正方形内绘制完整的 UIImage。我的问题是我怎样才能让我的代码工作。我的代码所做的是裁剪成正方形大小。我是 IO 的新手,任何人都可以提供帮助。

PS 我需要调用 CGcontext 的方法。

谢谢。

- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
CGSize size = [source size];
CGFloat width = size.width;
CGFloat height = size.height;
CGSize resizedImageSize;
if (width < height) {
resizedImageSize = CGSizeMake(height, height);
}else {
resizedImageSize = CGSizeMake(width, width);
}
UIGraphicsBeginImageContext(resizedImageSize);
CGRect rect = CGRectMake(0, 0, resizedImageSize.width, resizedImageSize.height);
[source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
CGContextStrokeRect(context, rect);
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}

我正在寻找的结果类型。

enter image description here

最佳答案

在 swift 3 中

extension UIImage {

func squareMe() -> UIImage {

var squareImage = self
let maxSize = max(self.size.height, self.size.width)
let squareSize = CGSize(width: maxSize, height: maxSize)

let dx = CGFloat((maxSize - self.size.width) / 2)
let dy = CGFloat((maxSize - self.size.height) / 2)

UIGraphicsBeginImageContext(squareSize)
var rect = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)

if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(UIColor.clear.cgColor)
context.fill(rect)

rect = rect.insetBy(dx: dx, dy: dy)
self.draw(in: rect, blendMode: .normal, alpha: 1.0)

if let img = UIGraphicsGetImageFromCurrentImageContext() {
squareImage = img
}
UIGraphicsEndImageContext()

}

return squareImage
}

}

关于ios - 如何在边缘为白色的正方形内绘制完整的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404051/

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