10

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?

Alex Smolov
  • 1,831
  • 4
  • 24
  • 43

3 Answers3

6

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.

Bhargavi
  • 515
  • 4
  • 14
  • The problem is that images I have are user-uploaded. Is there way to adjust it somehow from code? – Alex Smolov Apr 26 '15 at 14:09
  • @AlexSmolov it would be recommended to use `UIImageView` and set `ContentMode` to ` UIViewContentModeScaleAspectFit` – Bhargavi Apr 26 '15 at 14:19
  • @AlexSmolov this question and its answers will be helpful to you i guess [UIImageView aspect fit and center](http://stackoverflow.com/questions/15499376/uiimageview-aspect-fit-and-center) – Bhargavi Apr 26 '15 at 14:20
  • Thanks, but in addition to that I need my pattern to tile. – Alex Smolov Apr 26 '15 at 14:25
  • 1
    reduce the size of the image and then apply it as a background pattern. [resuce image size](http://stackoverflow.com/questions/612131/whats-the-easiest-way-to-resize-optimize-an-image-size-with-the-iphone-sdk) – Bhargavi Apr 26 '15 at 14:31
6

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!)
David Berry
  • 40,941
  • 12
  • 84
  • 95
0

Try this

 self.mainView.layer.contents = (id)[UIImage imageNamed:@"CROPNET.png"].CGImage;
vijay
  • 1,475
  • 2
  • 16
  • 26