简体   繁体   English

如何在不拉伸的情况下在UIView中填充背景图像

[英]How to fill the background image in a UIView without streching it

I'm trying to set the background image of a UIView with animated .gif's that I'm pulling form Giphy. 我试图设置动画形式的.gif来设置UIView的背景图像,这是我从Giphy中提取的。

The problem I'm having is that the UIView is stretching the image. 我遇到的问题是UIView正在拉伸图像。 I want to fill the background so the height is 100% and have it centered. 我想填充背景,使高度为100%,并使其居中。 So left and right of the .gif would be cut off - but the image would be centered on the screen and not stretched. 因此,.gif的左右将被切除-但图像将在屏幕上居中而不被拉伸。

Here's a screenshot of what it looks like now. 这是现在的屏幕截图。

You can see it's fills height correct but it's shrinking the width of the image to match the UIView dimensions making it look stretched. 您可以看到它的填充高度正确,但是它正在缩小图像的宽度以匹配UIView尺寸,从而使其看起来很拉伸。

Here is the code I have now: 这是我现在拥有的代码:

override func viewDidAppear(animated: Bool) {
    self.giphyBackground(Title: "dancing") { [weak self] (gifUrl) -> Void in
        let gifView = FLAnimatedImageView(frame: self!.giphy.frame)
        gifView.animatedImage = FLAnimatedImage(animatedGIFData: NSData(contentsOfURL: NSURL(string: gifUrl)!)!)
        self?.view.insertSubview(gifView, aboveSubview: self!.giphy)
    }
}

Any ideas 有任何想法吗

I think you should set the content mode of gifView to Aspect Fit , doing so will not stretch the image and will fully fill at-least one of the length either horizontally/ vertically. 我认为您应该将gifView的内容模式设置为Aspect Fit ,这样将不会拉伸图像,并且将在水平/垂直方向上完全填充至少一个长度。

Try setting 尝试设定

gifView.contentMode = UIViewContentMode.ScaleAspectFit

Also you can use scale AspectFill on gifView as 您也可以使用scale AspectFillgifView

gifView.contentMode = UIViewContentMode.ScaleAspectFill

ScaleAspectFill will fill the entire gifView's frame but will also maintain the aspect ratio, doing so your image won't look stretched but it could happen that content either horizontally or vertically will go outside the frame(which you can clip). ScaleAspectFill将填满整个gifView的框架,但也将保持纵横比,这样做不会使图像看起来被拉伸,但是水平或垂直的内容可能会超出框架(您可以对其进行裁剪)。

You are definitely looking for the view's contentMode ScaleAspectFit . 您肯定是在寻找视图的contentMode ScaleAspectFit Simply add a line gifView.contentMode=UIViewContentMode.ScaleAspectFit 只需添加一行gifView.contentMode=UIViewContentMode.ScaleAspectFit

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

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