Search code examples
iosswiftuilabel

How to fit background image of label to the frame size of a label


self.backgroundColor = UIColor(patternImage: UIImage(named: "na72.png")!)

(UILABEL)

How to fit background image of label to the frame size of a label? I should use 'self.backgroundColor = UIColor(~~)'


Solution

  • Because you are creating a UIColor using a patternimage, it is designed to create a tile pattern.

    To work around this, you can resize your image to match the size of the frame of your label manually, or by using a function (like this one), then use your resized image as your patternimage.

    Example using the above function:

    let image = imageWithImage(image: UIImage(named: "na72.png")!, scaledToSize: label.frame.size)
    label.backgroundColor = UIColor(patternImage: image)
    

    This issue was also discussed here