Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make image-based tiled background for UIView so that it doesn't scale?

Tags:

ios

swift

uiimage

In iOS application, I have 250x85pt UIView. I would like it to have image-based tiled background. The original image is 398x398 px. I would like my image to tile.

enter image description here

When I run application, my image tiles, but for some reason it scales as follows:

enter image description here

I used the following code to achieve it:

var image = UIImage(contentsOfFile: "myfilepath.png")!
var uicolor = UIColor(patternImage: image)
uiview.backgroundColor = uicolor

Could you explain 1. why ios scales my image, and 2. how do I draw tiled image without scaling?

like image 658
Alex Smolov Avatar asked Apr 26 '15 13:04

Alex Smolov


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I change the opacity of an image in Swift?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

What is UIImage in Swift?

An object that manages image data in your app.

What is Imageview in Swift?

A view that displays a single image or a sequence of animated images in your interface.


2 Answers

basically the image is bigger than your UIView. when you give UIColor(patternImage: image) it uses 1x size of the image. The image we usually laptops are scaled to window size with its aspect ratio.

So scale your image to your requirement and then apply it as background image.

like image 178
Bhargavi Avatar answered Oct 08 '22 17:10

Bhargavi


To expand on Banto's answer, the issue is that your view is 250x85 points, which, on retina devices is really 500x170 pixels. When your x1 image is turned into a pattern it is applied at the point level. The problem can be easily changed by setting the scale on the image to match the scale on the device:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 85))

let image = UIImage(named: "myfilepath.png")!
let scaled = UIImage(CGImage: image.CGImage, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)

view.backgroundColor = UIColor(patternImage: scaled!)
like image 41
David Berry Avatar answered Oct 08 '22 17:10

David Berry