2017-08-25 25 views
0

我正在關注this dicussion並獲得了原始圖像的分割部分的圖像陣列。如果我打印它,它看起來像這樣:如何在將一個圖像分成多個部分後,在Swift中使用UIImage數組?

[<UIImage: 0x61000008ea60>, {309, 212}, <UIImage: 0x61000008ec90>, {309, 212}, <UIImage: 0x61000008ebf0>, {309, 213}, <UIImage: 0x61000008ec40>, {309, 213}] 

我該如何使用此數組的元素?在常規情況下,我會使用圖像的名稱,例如,可以使用UIImage(named: "")。該數組不顯示任何名稱。你有什麼主意嗎?

也許我的錯誤是在這裏:

func setImage(){ 


     testImage = UIImageView(frame: CGRect(x: 0, y: 0, width: size/1.5, height: size/1.5)) 
     testImage.center = CGPoint(x: view.frame.width/2, y: view.frame.height/2) 


     slice(image: UIImage(named:"leopard_PNG14834")!, into: 8) 

     testImage.image = images[2] 


     view.addSubview(testImage) 


} 

下面是函數代碼

func slice(image: UIImage, into howMany: Int) -> [UIImage] { 
    let width: CGFloat 
    let height: CGFloat 

    switch image.imageOrientation { 
    case .left, .leftMirrored, .right, .rightMirrored: 
     width = image.size.height 
     height = image.size.width 
    default: 
     width = image.size.width 
     height = image.size.height 
    } 

    let tileWidth = Int(width/CGFloat(howMany)) 
    let tileHeight = Int(height/CGFloat(howMany)) 

    let scale = Int(image.scale) 


    let cgImage = image.cgImage! 

    var adjustedHeight = tileHeight 

    var y = 0 
    for row in 0 ..< howMany { 
     if row == (howMany - 1) { 
      adjustedHeight = Int(height) - y 
     } 
     var adjustedWidth = tileWidth 
     var x = 0 
     for column in 0 ..< howMany { 
      if column == (howMany - 1) { 
       adjustedWidth = Int(width) - x 
      } 
      let origin = CGPoint(x: x * scale, y: y * scale) 
      let size = CGSize(width: adjustedWidth * scale, height: adjustedHeight * scale) 
      let tileCgImage = cgImage.cropping(to: CGRect(origin: origin, size: size))! 
      images.append(UIImage(cgImage: tileCgImage, scale: image.scale, orientation: image.imageOrientation)) 
      x += tileWidth 
     } 
     y += tileHeight 
    } 
    return images 
} 
+0

請詳細介紹一下。你想對圖像做什麼?你可以通過它們在數組中的索引訪問它們。 –

+0

「尺寸」在哪裏定義? –

+0

size = view.frame.width – Roman

回答

0

如果你有一個很難將你的圖片到你的ViewController,這是你會使用這樣做的常見的方法,假設圖像陣列的輸入:

let image = images[0] 
let imageView = UIImageView(image: image) 
self.view.addSubview(imageView) 

編輯

如果你搞亂了圖像視圖的框架,我建議你在用上面的圖像初始化UIImageView之後再做。要測試發生了什麼,也許只需添加一個帶有所需圖像的ImageView,而不會混淆幀。然後檢查你用來設置框架的變量。

+0

太棒了!非常感謝! – Roman

+0

不用擔心,很高興幫助:) –

0

你已經獲得與UIImage類型的對象的數組。

let images = slice(image: someOriginalImage, into: 4) 
let firstImage = images[0] // firstImage is a UIImage 

{309, 212}是圖像的大小。

相關問題