Jace Jace - 4 months ago 23
iOS Question

Bezier close path not getting filled

I am using Swift v2.2 and I have drawn a rectangle as shown below which I intend to fill to then display some white text in it. However, I see the path has been closed but the rectangle is not getting filled. Please help and thanks for any input.

Code

class InstructionArrowBorderView: UIView {

var lineWidth: CGFloat = 1 {didSet { setNeedsDisplay() } }
var instructionRectPathColor: UIColor = UIColor(red:13/255.0, green:118/255.0, blue:255/255.0, alpha: 1.0) { didSet { setNeedsDisplay() } }

override func drawRect(rect: CGRect) {

let instructionRectPath = UIBezierPath()
instructionRectPath.moveToPoint(CGPoint(x: bounds.minX, y: bounds.maxY - 50))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.minX, y: bounds.minY))
instructionRectPath.moveToPoint(CGPoint(x: bounds.minX, y: bounds.minY))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.minY))
instructionRectPath.moveToPoint(CGPoint(x: bounds.maxX, y: bounds.minY))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.maxY - 50))
instructionRectPath.moveToPoint(CGPoint(x: bounds.maxX, y: bounds.maxY - 50))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.minX, y: bounds.maxY - 50))
instructionRectPath.lineWidth = lineWidth
instructionRectPath.closePath()
instructionRectPath.fill()
instructionRectPathColor.set()
instructionRectPath.stroke()
}
}


Layout


  • Cell


    • View (where Bezier's path is drawn)


      • Label (with white text)





Result
enter image description here

Answer

You are introducing discontinuities into your path. When you say addLineToPoint you don't also need to say moveToPoint which is preventing your path from filling correctly. You also want to set the color fill/stroke color then fill/stroke the path.

Your drawRect code should be:

let instructionRectPath = UIBezierPath()
instructionRectPath.moveToPoint(CGPoint(x: bounds.minX, y: bounds.maxY - 50))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.minX, y: bounds.minY))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.minY))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.maxX, y: bounds.maxY - 50))
instructionRectPath.addLineToPoint(CGPoint(x: bounds.minX, y: bounds.maxY - 50))
instructionRectPath.closePath()
instructionRectPath.lineWidth = lineWidth
instructionRectPathColor.set()
instructionRectPath.fill()
instructionRectPath.stroke()

Which could be written even more concisely as:

let instructionRectPath = UIBezierPath(rect: CGRect(x: bounds.minX, y: bounds.minY, width: bounds.maxX, height: bounds.maxY - 50))
instructionRectPath.lineWidth = lineWidth
instructionRectPathColor.set()
instructionRectPath.fill()
instructionRectPath.stroke()