Search code examples
iosswiftcore-graphicsuigraphicscontext

Drawing color picker/wheel with CoreGraphics creates black lines between colors


The Swift below creates a color picker/wheeler. It mostly works, but there are black bars between different color bands as illustrated by the attachment.

Adjusting for the device scale did not help.

Any ideas?

enter image description here

// Constants
let Saturation = CGFloat(0.88)
let Brightness = CGFloat(0.88)
let MaxHueValues = 360
let Hues = (0...359).map { $0 }

override func drawRect(rect: CGRect) {
    // Set context & adapt to screen resolution
    let context = UIGraphicsGetCurrentContext()
    //let scale = UIScreen.mainScreen().scale
    //CGContextScaleCTM(context, scale, scale)

    // Get height for each row
    rowHeight = frame.height / CGFloat(Hues.count)

    // Draw one hue per row
    for hue in Hues {
        let hueValue = CGFloat(hue) / CGFloat(MaxHueValues)
        let color = UIColor(hue: hueValue, saturation: Saturation, brightness: Brightness, alpha: 1.0)
        CGContextSetFillColorWithColor(context, color.CGColor)
        let yPos = CGFloat(hue) * rowHeight
        CGContextFillRect(context, CGRect(x: 0, y: yPos, width: frame.width, height: rowHeight))
    }
}

Solution

  • It's probably rounding errors. If your y position and height values are not integers then the system will try to interpolate your drawing to simulate sub-pixel rendering, and it really can't. Try adjusting your frame so it is an even multiple of the number of hues (so if have 360 hues, make your frame 360 points high, or 720 points.)