1

I have an UIImageView, which shows an UIImage, having content mode as Aspect Fit.

I need to indicate transparent areas of the images with a chessboard. How to obtain squares of the same size, no matter the size of the image?

extension UIImage {
    func withChessboard() -> UIImage? {
        var image: UIImage?
        let l = 4

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(UIColor.lightGray.cgColor)
            for row in 0 ..< Int(size.width) {
                for col in 0 ..< Int(size.height) {
                    if (row + col) % 2 == 0 {
                        context.fill(CGRect(x: col * l, y: row * l, width: l, height: l))
                    }
                }
            }

            draw(in: imageRect, blendMode: .normal, alpha: 1.0)
            image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }
}

Now I have this ( first image being smaller )

enter image description here

and this:

enter image description here

EDIT, using the solution suggested by Trent, I have obtained this. I need the tiles to cover just the size of the image, not the whole imageview. enter image description here

Laura Calinoiu
  • 704
  • 1
  • 8
  • 24

1 Answers1

0

Looks like this existing post has a clean answer to your solution.

Basically show you how to create a pattern with UIColor and set that as the backgroundColor of the UIImageView.

Let me know if that helps! If not, I'd like to hear why.

Trent
  • 3
  • 1
  • 6
  • Because uiimageview has `Aspect Fit` for the content, the tiles extend also where I don't have the image. I want tiles just behind the image, not on the whole imageview. – Laura Calinoiu Feb 14 '20 at 07:02
  • I've uploaded an image to the question to show you what I have obtained with the solution. But I need the tiles to be just behind the image, not to cover the whole imageview. Like I have on the pics above, but without the resize. – Laura Calinoiu Feb 14 '20 at 07:15