Search code examples
iosobjective-cquartz-2d

Draw line with oblique border


How to draw line with oblique border like this: oblique border

I drew only a normal line:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 30.f);
CGContextSetStrokeColorWithColor(context, [UIColor personalBlue].CGColor);
CGContextMoveToPoint(context, 0.f, 0.f);
CGContextAddLineToPoint(context,self.bounds.size.width, 0.f);
CGContextStrokePath(context);

Solution

  • I use CAShapeLayer:

    class TriangleView: UIView {
    
        override func awakeFromNib() {
            super.awakeFromNib()
            self.contentMode = UIViewContentMode.redraw
        }
    
        override func draw(_ rect: CGRect) {
            let mask = CAShapeLayer()
            mask.frame = self.layer.bounds
    
            let width = self.layer.frame.size.width
            let height = self.layer.frame.size.height
    
            let path = CGMutablePath.init()
    
            path.move(to: CGPoint(x: width, y: 0))
            path.addLine(to: CGPoint(x: width, y: height))
            path.addLine(to: CGPoint(x: 0, y: height))
            path.addLine(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: 0, y: 50))
    
            mask.path = path
    
            self.layer.mask = mask
    
            let shape = CAShapeLayer()
            shape.frame = self.bounds
            shape.path = path
            shape.lineWidth = 3.0
            shape.strokeColor = UIColor.white.cgColor
            shape.fillColor = UIColor.white.cgColor
    
            self.layer.insertSublayer(shape, at: 0)
        }
    
    
    }
    

    The result is this:

    enter image description here