簡體   English   中英

在UIImageView中更改UIImage的大小和位置(快速)

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

在Swift中,Im努力以編程方式在UIImageView中調整圖像(及其位置)的大小,如下所示:

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

在此處輸入圖片說明

我希望能夠使用相同的圖像使用上述houseImageView的裁剪/調整大小版本創建第二個imageView。 結果是顯示像這樣的網格中圖像的一部分。

在此處輸入圖片說明

我所有的調整大小的努力都得出以下錯誤結果。 我想我需要以某種方式調整圖像大小並更改imageView范圍? 如果需要,我可以發布很多示例失敗的代碼。

在此處輸入圖片說明

如果要創建尺寸為100,100的第二張圖像並將此圖像添加到以前的UIImageView ,則可以執行以下操作:

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM