如何在 UIImageView 中更改单个像素的图像

How to change the image of an individual pixel in UIImageView

提问人:Sharvan Kumawat 提问时间:4/1/2019 最后编辑:TheNeilSharvan Kumawat 更新时间:4/20/2019 访问量:181

问:

我有一个,我想更改其特定像素的图像,比如 100 x 100 像素。我该怎么做?UIImage

iOS iPhone UIImageView 像素

评论


答:

0赞 Sergio 4/1/2019 #1

您可以在该像素上添加一个矩形,并用颜色填充它:

var image: UIImage!
let color = UIColor.red
image = UIGraphicsImageRenderer(size: image.size).image { context in
    image.draw(at: .zero)
    let rectangle = CGRect(x: 100, y: 100, width: 1, height: 1)
    color.setFill()
    context.fill(rectangle)
}

或者,也许您想将 1 x 1 像素的 UIImage 嵌入到其他 UIImage 中:

var onePixel: UIImage!
var image: UIImage!
image = UIGraphicsImageRenderer(size: image.size).image { context in
    image.draw(at: .zero)
    onePixel.draw(at: CGPoint(x: 100, y: 100))
}

或者,您可能想将 UIImage 的一个像素移动到另一个 UIImage:

var image1: UIImage!
var image2: UIImage!
// 1 x 1 size image, from position 100 x 100 of image2
var pixel: UIImage = UIGraphicsImageRenderer(bounds: CGRect(x: 100, y: 100, width: 1, height: 1)).image(actions: { _ in
    image2.draw(at: .zero)
})
// The image1 with the pixel image embed in the position 100 x 100
var image1WithPixel = UIGraphicsImageRenderer(size: image1.size).image { (_) in
    image1.draw(at: .zero)
    pixel.draw(at: CGPoint(x: 100, y: 100))
}