pete
pete

Reputation: 3050

Changing the size and location of a UIImage within UIImageView (swift)

In Swift, Im struggling to programically resize an image ( and its location ) within a UIImageView as follows:

  var housePic = UIImage(named:"house")
  var houseImageView = UIImageView(image: housePic)

enter image description here

I want to be able create a 2nd imageView with a cropped / resized version of the above houseImageView using the same image. The result is to show a section of the image from a grid like this..

enter image description here

All my efforts of resizing gives the following wrong result. I think i need to somehow resize the image and change the imageView bounds ?? If required, I can post lots of example failed code.

enter image description here

Upvotes: 1

Views: 743

Answers (1)

Sebastian
Sebastian

Reputation: 6404

If you want to create a 2nd image with size 100,100 and add this image to the previous UIImageView you can do this:

    let imageName = "house.png"
    let originalImage = UIImage(named:imageName)!
    let imageView = UIImageView(image: originalImage)

    // this is only to visualization purpose
    imageView.backgroundColor = UIColor.lightGrayColor()

    self.view.addSubview(imageView)

    // create a new image resizing it
    let destinationSize = CGSizeMake(100, 100)
    UIGraphicsBeginImageContext(destinationSize);
    originalImage.drawInRect(CGRectMake(0,0,destinationSize.width,destinationSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();

    // add the new image to the UIImageView
    imageView.image = newImage
    imageView.contentMode = UIViewContentMode.Center

Upvotes: 2

Related Questions