我正在关注this dicussion并获得了一系列图像,这些图像是原始图像的分割部分。如果我打印它,它看起来像这样:
[<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)
您已经获得了一个包含UIImage
类型对象的数组。
let images = slice(image: someOriginalImage, into: 4)
let firstImage = images[0] // firstImage is a UIImage
{309, 212}
是图片的大小。
答案 1 :(得分:0)
如果您很难将图像添加到ViewController中,这是您常用的方法,假设输入了一组图像:
let image = images[0]
let imageView = UIImageView(image: image)
self.view.addSubview(imageView)
修改强>
如果您正在弄乱图像视图的框架,我建议您在使用上面的图像初始化UIImageView之后再进行此操作。要测试发生了什么,或许只需添加一个带有所需图像的ImageView,而不会弄乱框架。然后检查用于设置框架的变量。