I need to create a UIView that has the left border inclined with 45 degrees I was wondering,is there a way to acheive this programmatically? Does CATransform3D help me in this case since it’s not really a “3D rotation”?
Edit
Here's an image explaining more my needed output
If you just want the shape with no content then you can create a CAShapeLayer
and add it to your view's layer. (In fact you can also put content in there using this method but you'll need to alter it a bit).
CAShapeLayer *layer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 100)]; // bottom left corner
[path addLineToPoint:CGPointMake(100, 0)]; // top middle
[path addLineToPoint:CGPointMake(300, 0)]; // top right corner
[path addLineToPoint:CGPointMake(300, 100)]; // bottom right corner
[path closePath];
layer.path = path.CGPath;
layer.fillColor = [UIColor blackColor].CGColor;
layer.strokeColor = nil;
[theView.layer addSubLayer:layer];
This doesn't require using drawRect
or anything. You will have to change the coordinates based on the values you want.
You can also use a UIView
subclass and override drawRect
. It requires more work but the UIBezierPath
will be pretty much the same.
CALayer
is very powerful and used a lot by Apple. For instance the edit canvas in Pages is written almost exclusively using CALayer
s.
Resulted shape
Code in Swift5
class CustomView: UIView {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
// Get Height and Width
//let layerHeight = layer.frame.height
let layerWidth = layer.frame.width
// Create Path
let bezierPath = UIBezierPath()
// Points
let pointA = CGPoint(x: 0, y: 30)
let pointB = CGPoint(x: 20, y: 0)
let pointC = CGPoint(x: layerWidth, y: 0)
let pointD = CGPoint(x: layerWidth, y:30)
// Draw the path
bezierPath.move(to: pointA)
bezierPath.addLine(to: pointB)
bezierPath.addLine(to: pointC)
bezierPath.addLine(to: pointD)
bezierPath.close()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
layer.mask = shapeLayer
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With