简体   繁体   English

如何快速查看UIView的AspectFit背景图像?

[英]How to AspectFit Background image of UIView in swift?

when i set background image as pattern image then image is stretch so, i want to set as aspect-fit this pattern image so, how can do this? 当我将背景图像设置为图案图像然后将图像拉伸时,我想将此图案图像设置为宽高比适合,这怎么办?

 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!)

Thanks.. 谢谢..

There is a method in AVFoundation that might help you create an image in a particular size rect while keeping the aspect ratio. AVFoundation中有一种方法可以帮助您创建特定尺寸的图像,同时保持纵横比。 This will calculate the rect size based on the size that you provide, I used a maximum height since the original image is a landscape image. 这将根据您提供的大小来计算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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM