如何检索和显示存储在数组中的UIIMages?

时间:2016-03-28 05:10:16

标签: ios swift uiimageview uiimage core-graphics

我正在尝试将图像剪切成9块,将它们存储在一个数组中,然后在屏幕上随机重新分配。

我已经想出如何以编程方式创建一个新的UIIMageView并设置其背景颜色,以便我可以看到它的位置,但我无法获得用户所选图像(displayImageView.image)的裁剪部分按tiledView, UIImageView按钮后显示在randomize

我尝试将所有图块存储在tileStack数组中,每个图块的大小是displayImageView.image的1/3。不确定挂断是在我如何切片和存储图像,或者我是如何将数组元素调用到视图中。

(我只是试图让一块/瓷砖现在显示;稍后我将使用for循环来显示所有9件。)

//Beginning of function to cut photo into 9 tiles, then randomize them. 

//Cut selected image into 9 pieces and add each cropped image to tileStack array. 

@IBAction func randomize(sender: AnyObject) {

let tileSize = CGSizeMake(displayImageView.image!.size.width/3, displayImageView.image!.size.height/3)

    for (var rowI = 0; rowI < 3; rowI++)
    {
        for (var colI = 0; colI < 3; colI++)
        {
            let tileRect = CGRectMake(CGFloat(rowI) * tileSize.width, tileSize.height * CGFloat(colI), tileSize.width, tileSize.height)

            let tileImage = CGImageCreateWithImageInRect(displayImageView.image!.CGImage, tileRect)

            if let selectedImage = displayImageView.image
            {
                let tileImage = CGImageCreateWithImageInRect(selectedImage.CGImage, tileRect)
                tileStack.append(tileImage!)
            }

        }
    }

    //display tiles in order on screen

    var tiledView : UIImageView
    tiledView = UIImageView(frame:CGRectMake(50, 150, 100, 100))
    tiledView.backgroundColor = UIColor.redColor()
    tiledView.center = CGPointMake(150, 150)
    tiledView.image = tileStack[3] as? UIImage
    self.view.addSubview(tiledView)

}

1 个答案:

答案 0 :(得分:0)

CGImageCreateWithImageInRect(displayImageView.image!.CGImage,tileRect)返回一个CGImage,它实际上不是图像而是图像的位图表示,您应该使用下面的代码将CGImage转换为UIImage var aNewUIImage = UIImage(CGImage:imageRef) - @Ajay Beniwal