SNos
SNos

Reputation: 3470

Swift 2.2 - Split UIImage by 6X6 small Images

I am trying to divide a square UIImage into 36 images (6x6 frame)

In order to divide the image I am using an extension of UIImage that divide the image in half however, I cannot find the way to get the images fit in the grid.

Is there a Simple way for doing this?

extension UIImage {
    var topHalf: UIImage {
        return UIImage(CGImage: CGImageCreateWithImageInRect(CGImage, CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height/2)))!, scale: 1, orientation: imageOrientation)
    }
    var bottomHalf: UIImage {
        return UIImage(CGImage: CGImageCreateWithImageInRect(CGImage, CGRect(origin: CGPoint(x: 0,  y: CGFloat(Int(size.height)-Int((size.height/2)))),  size: CGSize(width: size.width, height: CGFloat(Int(size.height)-Int((size.height/2))))))!, scale: 1, orientation: imageOrientation)
    }
    var leftHalf: UIImage {
        return UIImage(CGImage: CGImageCreateWithImageInRect(CGImage, CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width/2, height: size.height)))!, scale: 1, orientation: imageOrientation)
    }
    var rightHalf: UIImage {
        return UIImage(CGImage: CGImageCreateWithImageInRect(CGImage, CGRect(origin: CGPoint(x: CGFloat(Int(size.width)-Int((size.width/2))), y: 0), size: CGSize(width: CGFloat(Int(size.width)-Int((size.width/2))), height: size.height)))!, scale: 1, orientation: imageOrientation)
    }
}

enter image description here

Upvotes: 0

Views: 708

Answers (1)

Duncan C
Duncan C

Reputation: 131436

You want a 6/6 grid of images. The code you have divides an image in half. You can't get 1/6ths out of halves. You will need to change the code to give you 6ths. I suggest you write a method that takes as parameters:

  • A UIImage.
  • A total number of rows
  • A total number of columns
  • A row index
  • A column index

And returns an image at that grid position. It would involve doing some math to calculate the origin and size of the rectangle for that grid position and then uses CGImageCreateWithImageInRect to extract the image in question.

Upvotes: 1

Related Questions