gpt4 book ai didi

ios - 如何在 swift 中对 UIView 的 AspectFit 背景图像进行 AspectFit?

转载 作者:行者123 更新时间:2023-11-28 13:51:54 24 4
gpt4 key购买 nike

当我将背景图像设置为图案图像时,图像会被拉伸(stretch),所以我想将此图案图像设置为纵横比适合,如何才能做到这一点?

 let Image1 = UIImage(named: KeyboardBG_image)
UIGraphicsBeginImageContext(keyboardview.frame.size);
Image1?.draw(in: keyboardview.bounds);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = UIColor(patternImage: image!)

谢谢..

最佳答案

AVFoundation 中有一种方法可以帮助您创建特定大小的矩形图像,同时保持纵横比。这将根据您提供的尺寸计算矩形尺寸,我使用了最大高度,因为原始图像是横向图像。

/* create the image at original size */
let image1 = UIImage(named: "Landscape-1276x800.jpg")!

/*
* create bounding rect with largest possible height based on width
* this will get you the aspect height for the specified width
*/
let boundingRect = CGRect(x: 0, y: 0, width: 200, height:CGFloat.greatestFiniteMagnitude)

/*
* Returns a scaled CGRect that maintains the aspect ratio specified
* by a CGSize within a bounding CGRect
*/
let aspectRect = AVMakeRect(aspectRatio: image1.size, insideRect: boundingRect)

/*
* create a UIGraphicsImageRenderer to draw the image, this replaces all
* the UIGraphicsContext stuff that was used to draw images
*/
let renderer = UIGraphicsImageRenderer(size: aspectRect.size)

/*
* WARNING be careful about the origin points, if the result of the calculation
* is an exponential value like 8.988465674311579e+307, then the image won't draw.
* To be safe I set the origin to .zero
*/
let img = renderer.image { (context) in
image1.draw(in: CGRect(origin: .zero, size: aspectRect.size))
}

关于ios - 如何在 swift 中对 UIView 的 AspectFit 背景图像进行 AspectFit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54490301/

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