How to make a CAshapeLayer fit into a button? - swift

I tried to create a function inside a custom UIButton class to add a shape to an existing button.
func drawStartButton(){
let shape = CAShapeLayer()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 500, y: 0))
path.addLine(to: CGPoint(x: 500, y: -100))
path.addLine(to: CGPoint(x: 250, y: -50))
path.addLine(to: CGPoint(x: 0, y: -100))
path.addLine(to: CGPoint(x: 0, y: 0))
path.close()
shape.path = path.cgPath
shape.fillColor = redColor.cgColor
shape.frame = self.bounds
self.layer.addSublayer(shape)
}
So far no problem... BUT when i add the layer to the button, the layer is to big of course! How can i "autoresize" the layer to its button? I did expect something like
shape.frame = self.bounds
... but the path still keeps the same size as without the self.bounds.

Your best bet is to subclass the button and then layout your layer in layoutSubviews which gets called when your surrounding frame changes.
final class StartButton: UIButton {
private let shapeLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.frame = bounds
}
}
But I'm noticing that you are dictating a giant shape in terms of your CGPoints. You might have to subclass the layer, too, and redraw based on your bounds in layoutSublayers.

class CustomShapeCAshapeLayer: CAShapeLayer {
func shapeButton(width: CGFloat, height: CGFloat){
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: width, y: 0))
path.addLine(to: CGPoint(x: width, y: height + 30))
path.addLine(to: CGPoint(x: width/2, y: height))
path.addLine(to: CGPoint(x: 0, y: height + 30))
path.addLine(to: CGPoint(x: 0, y: 0))
path.close()
self.fillColor = redColor.cgColor
self.path = path.cgPath
}
}
main:
let layer = CustomShapeCAshapeLayer()
layer.shapeButton(width: startGameButton.frame.width, height: startGameButton.frame.height)
startGameButton.layer.addSublayer(layer)

Related

How to give corner radius in one side to Imageview in swift?

How can I give corner radius in one side to Imageview like zig zag?
like in image
In this image I want like a large image witch is highlighted in Blue line.
If anyone know about this Please help me.
And I apologize if I could not explane my problem properly.
Solve the problem using bezier path
Study the bezier path principle and find the appropriate control point
Here is the sample code
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height/3))
let path = UIBezierPath()
path.move(to: CGPoint(x: 0.0, y: 0.0))
path.addLine(to: CGPoint(x: self.view.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.view.frame.width, y: self.view.frame.size.height/3))
path.addCurve(to: CGPoint(x: 0, y: self.view.frame.size.height/3 - 50),
controlPoint1: CGPoint(x: 200, y: self.view.frame.size.height/3 - 20),
controlPoint2: CGPoint(x: self.view.frame.width/2, y: self.view.frame.size.height/3 - 100))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
imageView.layer.mask = shapeLayer
imageView.image = UIImage(named: "spider.jpg")
self.view.addSubview(imageView)

How to curve edges of UIImageview in swift ios?

I used
let view = UIImageView(CGRect(x: 0, y: 10, width: 100, height: 100))
view.cornerRadius = 10
self.mainView.addSubview(view)
This rounds the corner I want round the edges
The standard technique is to
Define a UIBezierPath for the shape.
Make a CAShapeLayer using that path.
Define the image view’s layer’s mask to use that shape layer.
E.g.
#IBDesignable
class RoundedCornerView: UIImageView {
#IBInspectable
var cornerRadius: CGFloat = 17 { didSet { setNeedsLayout() } }
#IBInspectable
var lineWidth: CGFloat = 75 { didSet { setNeedsLayout() } }
override func layoutSubviews() {
super.layoutSubviews()
let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
let path = UIBezierPath()
var point = CGPoint(x: rect.minX + cornerRadius, y: rect.minY + cornerRadius)
path.move(to: point)
var controlPoint = CGPoint(x: point.x + cornerRadius, y: rect.minY)
point = CGPoint(x: rect.midX, y: rect.minY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
point = CGPoint(x: rect.maxX - cornerRadius, y: rect.minY + cornerRadius)
controlPoint = CGPoint(x: point.x - cornerRadius, y: rect.minY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
controlPoint = CGPoint(x: rect.maxX, y: point.y + cornerRadius)
point = CGPoint(x: rect.maxX, y: rect.midY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
point = CGPoint(x: rect.maxX - cornerRadius, y: rect.maxY - cornerRadius)
controlPoint = CGPoint(x: rect.maxX, y: point.y - cornerRadius)
path.addQuadCurve(to: point, controlPoint: controlPoint)
controlPoint = CGPoint(x: point.x - cornerRadius, y: rect.maxY)
point = CGPoint(x: rect.midX, y: rect.maxY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
point = CGPoint(x: rect.minX + cornerRadius, y: rect.maxY - cornerRadius)
controlPoint = CGPoint(x: point.x + cornerRadius, y: rect.maxY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
controlPoint = CGPoint(x: rect.minX, y: point.y - cornerRadius)
point = CGPoint(x: rect.minX, y: rect.midY)
path.addQuadCurve(to: point, controlPoint: controlPoint)
point = CGPoint(x: rect.minX + cornerRadius, y: rect.minY + cornerRadius)
controlPoint = CGPoint(x: rect.minX, y: point.y + cornerRadius)
path.addQuadCurve(to: point, controlPoint: controlPoint)
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = UIColor.white.cgColor
layer.mask = shapeLayer
clipsToBounds = true
}
}
Yields:
You’ll have to play around with values for cornerRadius and lineWidth for your image view’s dimensions, but hopefully this illustrates the idea. The default values I used in the code above was for a 300×300 image view.
Note, I implemented the path in layoutSubviews so that it would respond to resizing of your image view. I also make it #IBDesignable so that you could see it rendered in IB if you happened to be using storyboards.
Try to wrap image inside UIView
let image = UIImageView(CGRect(x:0,y:0,width:100,height:100))
let view = UIView(CGRect(x:0,y:10,width:100,height:100))
view.cornerRadius = 10
view.addSubiew(image)
self.mainView.addSubview(view)
Swift 4
let image = UIImageView(frame: CGRect(x:0,y:0,width:100,height:100))
let view = UIView(frame: CGRect(x:0,y:10,width:100,height:100))
view.layer.cornerRadius = 30
view.addSubview(image)
self.mainView.addSubview(view)

How to cut of corners of UIButton, not round them?

I would like to cut the corners off of a UIButton in swift.
I know how to set a corner radius but I'd like to cut the corners.
// what I DON'T want, rounded corners
myButton.layer.cornerRadius = myButton.frame.height / 2
Cut off corners are for me:
Create a CAShapeLayer with the desired path like this
let button = UIButton()
button.backgroundColor = .red
button.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
view.addSubview(button)
let layer = CAShapeLayer()
layer.fillColor = UIColor.yellow.cgColor
let cutSize:CGFloat = 20
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: button.bounds.midY))
path.addLine(to: CGPoint(x: cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX, y: button.bounds.midY))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: 0, y: button.bounds.midY))
layer.path = path.cgPath
button.layer.insertSublayer(layer, at: 0)
You can achieve by following:
sampleButton.layer.cornerRadius = 15
sampleButton.clipsToBounds = true

How to create Right Angle View in Swift?

I am able to create triangle view in swift using below code-
class TriangleView: UIView {
override func draw(_ rect: CGRect) {
// Get Height and Width
let layerHeight = layer.frame.height
let layerWidth = layer.frame.width
// Create Path
let bezierPath = UIBezierPath()
// Draw Points
bezierPath.move(to: CGPoint(x: 0, y: layerHeight))
bezierPath.addLine(to: CGPoint(x: layerWidth, y: layerHeight))
bezierPath.addLine(to: CGPoint(x: layerWidth / 2, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: layerHeight))
bezierPath.close()
// Apply Color
UIColor.red.setFill()
bezierPath.fill()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
layer.mask = shapeLayer
}
}
override func viewDidLoad() {
super.viewDidLoad()
let triangle = TriangleView(frame: CGRect(x: 0, y: 0, width: 55 , height: 60))
triangle.backgroundColor = .white
triangle.transform = CGAffineTransform(rotationAngle: .pi * 4.49)
imageView.addSubview(triangle)
}
Now problem is that I want to change it to the right angle triangle using transform properties. How to achieve this?
Expected Result
Current Result
I hope you want this part.
Here is the code.
override func draw(_ rect: CGRect) {
let path = UIBezierPath.init()
// top left
path.move(to: .zero)
// top right
path.addLine(to: CGPoint(x: bounds.size.width,
y: 0))
// bottom left offset
path.addLine(to: CGPoint(x: bounds.size.width * 0.1,
y: bounds.size.height))
// bottom left
path.addLine(to: CGPoint(x: 0,
y: bounds.size.height))
// top left
path.close()
// change fill color here.
UIColor.black.setFill()
path.fill()
}
Result
How I drew
Modification
If you change the code UIColor.black.setFill() to
let fillColor = UIColor(red: 0xF9/0xff, green: 0x0D/0xff, blue: 0x5A/0xff, alpha: 1)
fillColor.setFill()
you get this result.
Have fun coding.
You're currently drawing 'a'. You want to draw 'b'.
extension UIBezierPath {
convenience init(rightAngledTriangleInRect: CGRect, offset withOffset: CGFloat) {
self.init()
move(to: CGPoint(x: rect.minX, y: rect.minY))
addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
addLine(to: CGPoint(x: rect.minX + offset, y: rect.maxY))
addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
addLine(to: CGPoint(x: rect.minX, y: rect.minY))
close()
}
}
Then use by:
let path = UIBezierPath.init(rightAngledTriangleInRect: rect, withOffset: 20.0)
Note that there's no need to add self. in the convenience inits for the bezier path instructions.
If you're doing a lot of drawing, I'd recommend adding a number of these inits to make life easier.
To use in your current TriangleView:
class TriangleView: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath.init(rightAngledTriangleInRect: rect, withOffset: 20.0)
let shape = CAShapeLayer()
shape.path = path.cgPath
// Set the mask
layer.mask = shape
}
}
There are some easy way too for achivieng this but for using transform here is the sample code.use this transform instead of yours.it's sample code for having right angle triangle from your drawing:
triangle.transform = CGAffineTransform.identity.rotated(by: CGFloat.pi).translatedBy(x: (triangle.bounds.width / 2), y: 0.0)
you should notice that CGAffineTransform rotate the view from it's origins

Swift draw shadow to a uibezier path

I have a strange question. Even though I did read a lot of tutorials on how to do this, the final result only shows the bezier line, not any shadow whatsoever. My code is pretty simple :
let borderLine = UIBezierPath()
borderLine.moveToPoint(CGPoint(x:0, y: y! - 1))
borderLine.addLineToPoint(CGPoint(x: x!, y: y! - 1))
borderLine.lineWidth = 2
UIColor.blackColor().setStroke()
borderLine.stroke()
let shadowLayer = CAShapeLayer()
shadowLayer.shadowOpacity = 1
shadowLayer.shadowOffset = CGSize(width: 0,height: 1)
shadowLayer.shadowColor = UIColor.redColor().CGColor
shadowLayer.shadowRadius = 1
shadowLayer.masksToBounds = false
shadowLayer.shadowPath = borderLine.CGPath
self.layer.addSublayer(shadowLayer)
What am I doing wrong as I dont seem to see anything wrong but of course I am wrong since no shadow appears. The function is drawRect, basic UIVIew no extra anything in there, x and y are the width and height of the frame. Many thanks in advance!
I take this example straight from my PaintCode-app. Hope this helps.
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Shadow Declarations
let shadow = UIColor.blackColor()
let shadowOffset = CGSizeMake(3.1, 3.1)
let shadowBlurRadius: CGFloat = 5
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(30.5, 90.5))
bezier2Path.addLineToPoint(CGPointMake(115.5, 90.5))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, (shadow as UIColor).CGColor)
UIColor.blackColor().setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
CGContextRestoreGState(context)
I prefer the way to add a shadow-sublayer. You can easily use the following function (Swift 3.0):
func createShadowLayer() -> CALayer {
let shadowLayer = CALayer()
shadowLayer.shadowColor = UIColor.red.cgColor
shadowLayer.shadowOffset = CGSize.zero
shadowLayer.shadowRadius = 5.0
shadowLayer.shadowOpacity = 0.8
shadowLayer.backgroundColor = UIColor.clear.cgColor
return shadowLayer
}
And finally, you just add it to your line path (CAShapeLayer):
let line = CAShapeLayer()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 50, y: 100))
path.addLine(to: CGPoint(x: 100, y: 50))
line.path = path.cgPath
line.strokeColor = UIColor.blue.cgColor
line.fillColor = UIColor.clear.cgColor
line.lineWidth = 2.0
view.layer.addSublayer(line)
let shadowSubLayer = createShadowLayer()
shadowSubLayer.insertSublayer(line, at: 0)
view.layer.addSublayer(shadowSubLayer)
I am using the shadow properties of my shape layer to add shadow to it. The best part of this approach is that I don't have to provide a path explicitly. The shadow follows the path of the layer. I am also animating the layer by changing path. In that case too the shadow animates seamlessly without a single line of code.
Here is what I am doing (Swift 4.2)
shapeLayer.path = curveShapePath(postion: initialPosition)
shapeLayer.strokeColor = UIColor.clear.cgColor
shapeLayer.fillColor = shapeBackgroundColor
self.layer.addSublayer(shapeLayer)
if shadow {
shapeLayer.shadowRadius = 5.0
shapeLayer.shadowColor = UIColor.gray.cgColor
shapeLayer.shadowOpacity = 0.8
}
The curveShapePath method is the one that returns the path and is defined as follows:
func curveShapePath(postion: CGFloat) -> CGPath {
let height: CGFloat = 37.0
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0)) // start top left
path.addLine(to: CGPoint(x: (postion - height * 2), y: 0)) // the beginning of the trough
// first curve down
path.addCurve(to: CGPoint(x: postion, y: height),
controlPoint1: CGPoint(x: (postion - 30), y: 0), controlPoint2: CGPoint(x: postion - 35, y: height))
// second curve up
path.addCurve(to: CGPoint(x: (postion + height * 2), y: 0),
controlPoint1: CGPoint(x: postion + 35, y: height), controlPoint2: CGPoint(x: (postion + 30), y: 0))
// complete the rect
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: 0, y: self.frame.height))
path.close()
return path.cgPath
}