Ali
Ali

Reputation: 5121

Swift 4 - Create UIView with 2 background colors

I have a UIView having equal width/height as of its superview. This is what I want to get.

enter image description here

For the time being I have used a static background image. Any ideas?

Upvotes: 1

Views: 1481

Answers (2)

MhmdRizk
MhmdRizk

Reputation: 1721

enter image description here

swift 4: you can instead ,of making a view with several background colors, add sublayer to your view.

//connect your view.

@IBOutlet weak var yourView: UIView!


override func viewDidLoad() {
    super.viewDidLoad()

    //add a shape 
    let shape = CAShapeLayer()
    self.yourView.layer.addSublayer(shape)
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.black.cgColor

    // add your path 
    // you can simply adjust the points.
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: 0, y: (3*yourView.bounds.height)/4))
    path.addLine(to: CGPoint(x:self.yourView.bounds.width , y: yourView.bounds.height/2))
    path.addLine(to: CGPoint(x: self.yourView.bounds.width, y: 0))
    path.close()
    shape.path = path.cgPath

}

Upvotes: 1

Sahil Manchanda
Sahil Manchanda

Reputation: 10012

Result

Result

Code

import UIKit
@IBDesignable
public class AngleView: UIView {

    @IBInspectable public var fillColor: UIColor = .blue { didSet { setNeedsLayout() } }

    var points: [CGPoint] = [
        .zero,
        CGPoint(x: 1, y: 0),
        CGPoint(x: 1, y: 0.4),
        CGPoint(x: 0, y: 0.5)
        ] { didSet { setNeedsLayout() } }

    private lazy var shapeLayer: CAShapeLayer = {
        let _shapeLayer = CAShapeLayer()
        self.layer.insertSublayer(_shapeLayer, at: 0)
        return _shapeLayer
    }()

    override public func layoutSubviews() {
        shapeLayer.fillColor = fillColor.cgColor

        guard points.count > 2 else {
            shapeLayer.path = nil
            return
        }

        let path = UIBezierPath()

        path.move(to: convert(relativePoint: points[0]))
        for point in points.dropFirst() {
            path.addLine(to: convert(relativePoint: point))
        }
        path.close()

        shapeLayer.path = path.cgPath
    }

    private func convert(relativePoint point: CGPoint) -> CGPoint {
        return CGPoint(x: point.x * bounds.width + bounds.origin.x, y: point.y * bounds.height + bounds.origin.y)
    }
}

Source Just modified the values :D

Upvotes: 2

Related Questions