How do I Code pixel colors in a UIView using Swift maybe metal for iOS iPhone?

I’m using iOS on my iPhone and can create a UIView usually with some text added; But what I want to do is be able to code so that I can change the colors of the pixels within that UIView.
I imagine there is some function in Swift or metal that lets me do:

UIView.pixelColor(x,y,color).

Any suggestions welcome.

There isn't such a function, but you can do your custom drawing by overriding the draw(_ rect: CGRect) method.

A quick example of filling a view with squares of size elementSize with blues of decreasing transparency from left to right.

    override func draw(_ rect: CGRect) {

        let elementSize: CGFloat = 5

        let context = UIGraphicsGetCurrentContext()!
        
        for y in stride(from: 0.0, to: rect.height, by: elementSize) {
            for x in stride(from: 0.0, to: rect.width, by: elementSize) {

                let color = UIColor.blue.withAlphaComponent(x / rect.width)
                
                context.setFillColor(color.cgColor)
                context.fill(CGRect(x: x, y: y, width: elementSize, height: elementSize))
            }
        }
    }

This is how it looks:


If you want to know the ratio between a pixel and a point, you can use the screen's scale property UIScreen.main.scale or compare the screen's nativeBounds with it's bounds.

Also, consider this:

1 Like

Please ask Apple-related questions in the Apple developer forums.

2 Likes

Thank you. This helps me a lot by getting started in the right direction. I can learn from your example now and modify it as I need to.