当我设置背景图片的图案图像,然后图像被拉伸的话,我想将其设置为纵横适合这种模式像这样,怎么能做到这一点?
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))
}