如何在将一个图像分成多个部分后,在Swift中使用UIImage数组?

问题描述:

我正在关注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

如果你有一个很难将你的图片到你的ViewController,这是你会使用这样做的常见的方法,假设图像阵列的输入:

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

编辑

如果你搞乱了图像视图的框架,我建议你在用上面的图像初始化UIImageView之后再做。要测试发生了什么,也许只需添加一个带有所需图像的ImageView,而不会混淆帧。然后检查你用来设置框架的变量。

+0

太棒了!非常感谢! – Roman

+0

不用担心,很高兴帮助:) –

你已经获得与UIImage类型的对象的数组。

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

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