简体   繁体   中英

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)

在此处输入图片说明

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..

在此处输入图片说明

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.

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM