Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在swift中AspectFit UIView的背景图像?_Ios_Swift_Custom Keyboard_Aspect Fit - Fatal编程技术网

Ios 如何在swift中AspectFit UIView的背景图像?

Ios 如何在swift中AspectFit UIView的背景图像?,ios,swift,custom-keyboard,aspect-fit,Ios,Swift,Custom Keyboard,Aspect Fit,当我将背景图像设置为图案图像时,图像是拉伸的,所以,我想将背景图像设置为纵横比,以适合此图案图像,那么,如何才能做到这一点 let Image1 = UIImage(named: KeyboardBG_image) UIGraphicsBeginImageContext(keyboardview.frame.size); Image1?.draw(in: keyboardview.bounds); let image = UIGraphicsGetImageFromCu

当我将背景图像设置为图案图像时,图像是拉伸的,所以,我想将背景图像设置为纵横比,以适合此图案图像,那么,如何才能做到这一点

 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
中有一种方法可以帮助您在保持纵横比的同时创建特定大小的rect图像。这将根据您提供的大小计算rect大小,因为原始图像是横向图像,所以我使用了最大高度

/* 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))
}

您是否将视图的
cliptobunds
设置为true?可能的副本请查看使用UIColor(patternImage:)制作图案颜色,并将该颜色设置为UIView的
backgroundColor