Background
I’m attempting to draw a 3D cone shape as shown in the image below.
I have a method that I use to draw a simple triangle and fill it with a solid color in Swift using a UIBezierPath() and CAShapeLayer().
Question
In Swift code, how can I draw a 3D cone shape or fill the triangle
shape I’ve drawn with a complex gradient that gives the triangle shape
a 3D effect and effectively a cone appearance?
Code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 100))
path.addLineToPoint(CGPoint(x: 200, y: 100))
path.addLineToPoint(CGPoint(x: 100, y: 0))
path.closePath()
let shape = CAShapeLayer()
shape.path = path.CGPath
shape.fillColor = UIColor.grayColor().CGColor
myView.layer.insertSublayer(shape, atIndex: 0)
}
}
Image
I was able to achieve your goal making use of CGGradientLayer with a type of conic. The trick is to use the triangle shape as a mask for the gradient.
Here is an example that can be run in a Swift Playground. Comments in the code.
import UIKit
import PlaygroundSupport
class ConeView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
// Just for display
backgroundColor = .yellow
// Create the triangle to be used as the gradient's mask
// Base the size of the triangle on the view's frame
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: frame.height))
path.addLine(to: CGPoint(x: frame.width, y: frame.height))
path.addLine(to: CGPoint(x: frame.width / 2, y: 0))
path.close()
// Create a shape from the path
let shape = CAShapeLayer()
shape.path = path.cgPath
// Create a conical gradient and mask it with the triangle shape
let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: -0.5)
gradientLayer.type = .conic
// Change the white value of the center color to adjust the center highlight brightness as desired
gradientLayer.colors = [UIColor.black.cgColor, UIColor(white: 0.9, alpha: 1.0).cgColor, UIColor.black.cgColor]
// Tweak the 1st and 3rd number as desired.
// The closer to 0.5 the darker the cone edges will be.
// The further from 0.5 the lighter the cone edges will be.
gradientLayer.locations = [ 0.38, 0.5, 0.62 ]
gradientLayer.frame = bounds
gradientLayer.mask = shape
layer.insertSublayer(gradientLayer, at: 0)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Set whatever size you want for the view
PlaygroundPage.current.liveView = ConeView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
Here's the result (the black border is not part of the view, just part of the screen capture):
Related
class AttributedView: UIView {
private let gradient = CAGradientLayer()
var cornerRadius: CGFloat = 3 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
I simply use it for both: button view (corner radius: 20) and background circle (corner radius: 600).
Why button is smooth, and background is not?
With iOS 13.0 you can simple do, in addition to setting corner radius
yourView.layer.cornerCurve = .continuous
You should use bezzier paths and draw circle. After that you will receive nice, smooth edges.
let context = UIGraphicsGetCurrentContext()!
let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.white.cgColor] as CFArray, locations: [0, 1])!
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 64, y: 9, width: 111, height: 93))
context.saveGState()
ovalPath.addClip()
context.drawLinearGradient(gradient, start: CGPoint(x: 119.5, y: 9), end: CGPoint(x: 119.5, y: 102), options: [])
context.restoreGState()
UIBezierPath is a simple and efficient class for drawing shapes using Swift, which you can then put into CAShapeLayer, SKShapeNode, or other places. It comes with various shapes built in, so you can write code like this to create a rounded rectangle or a circle:
let rect = CGRect(x: 0, y: 0, width: 256, height: 256)
let roundedRect = UIBezierPath(roundedRect: rect, cornerRadius: 50)
let circle = UIBezierPath(ovalIn: rect)
You can also create custom shapes by moving a pen to a starting position then adding lines:
let freeform = UIBezierPath()
freeform.move(to: .zero)
freeform.addLine(to: CGPoint(x: 50, y: 50))
freeform.addLine(to: CGPoint(x: 50, y: 150))
freeform.addLine(to: CGPoint(x: 150, y: 50))
freeform.addLine(to: .zero)
If your end result needs a CGPath, you can get one by accessing the cgPath property of your UIBezierPath.
You probably should clip bounds of this view:
attributedView.clipsToBounds = true
I added a subview (with a black border) in a view and centered it.
Then I generate 2 identical triangles with CAShapeLayer and add one to the subview and the other to the main view.
Here is the visual result in Playground where we can see that the green triangle is totally off and should have been centered.
And here is the code:
let view = UIView()
let borderedView = UIView()
var containedFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
func setupUI() {
view.frame = CGRect(x: 0, y: 0, width: 300, height: 600)
view.backgroundColor = .white
borderedView.frame = containedFrame
borderedView.center = view.center
borderedView.backgroundColor = .clear
borderedView.layer.borderColor = UIColor.black.cgColor
borderedView.layer.borderWidth = 1
view.addSubview(borderedView)
setupTriangles()
}
private func setupTriangles() {
view.layer.addSublayer(createTriangle(color: .red)) // RED triangle
borderedView.layer.addSublayer(createTriangle(color: .green)) // GREEN triangle
}
private func createTriangle(color: UIColor) -> CAShapeLayer {
let layer = CAShapeLayer()
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: -containedFrame.width, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: -containedFrame.height))
bezierPath.close()
layer.position = borderedView.center
layer.path = bezierPath.cgPath
layer.fillColor = color.cgColor
return layer
}
Note: All position (of view, the borderedView and both triangles) are the same (150.0, 300.0)
Question: Why is the green layer not in the right position?
#DuncanC is right that each view has its own coordinate system. Your problem is this line:
layer.position = borderedView.center
That sets the layer's position to the center of the frame for the borderedView which is in the coordinate system of view. When you create the green triangle, it needs to use the coordinate system of borderedView.
You can fix this by passing the view to your createTriangle function, and then use the center of the bounds of that view as the layer position:
private func setupTriangles() {
view.layer.addSublayer(createTriangle(color: .red, for: view)) // RED triangle
borderedView.layer.addSublayer(createTriangle(color: .green, for: borderedView)) // GREEN triangle
}
private func createTriangle(color: UIColor, for view: UIView) -> CAShapeLayer {
let layer = CAShapeLayer()
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: -containedFrame.width, y: 0))
bezierPath.addLine(to: CGPoint(x: 0, y: -containedFrame.height))
bezierPath.close()
layer.position = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
layer.path = bezierPath.cgPath
layer.fillColor = color.cgColor
return layer
}
Note: When you do this, the green triangle appears directly below the red one, so it isn't visible.
Every view/layer uses the coordinate system of it's superview/superlayer. If you add a layer to self.view.layer, it will be positioned in self.view.layer's coordinate system. If you add a layer to borderedView.layer, it will be in borderedView.layer's coordinate system.
Think of the view/layer hierarchy as stacks of pieces of graph paper. You place a new piece of paper on the current piece (the superview/layer) in the current piece's coordinates system, but then if you draw on the new view/layer, or add new views/layer inside that one, you use the new view/layer's coordinate system.
I want to add an inner border to a view with a gradient. The following code works and gives me this result
import UIKit
class InnerGradientBorderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
super.draw(rect)
addGradientInnerBorder(width: 8, color: FlatWhite())
}
func addGradientInnerBorder(width: CGFloat, color: UIColor) {
// Setup
let topLeftO = CGPoint(x: 0, y: 0)
let topLeftI = CGPoint(x: width, y: width)
let topRightO = CGPoint(x: frame.width, y: 0)
let topRightI = CGPoint(x: frame.width - width, y: width)
let bottomLeftO = CGPoint(x: 0, y: frame.height)
let bottomLeftI = CGPoint(x: width, y: frame.height - width)
let bottomRightO = CGPoint(x: frame.width, y: frame.height)
let bottomRightI = CGPoint(x: frame.width - width, y: frame.height - width)
// Top
let topPoints = [topLeftO, topLeftI, topRightI, topRightO, topLeftO]
let topGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 1)]
addGradientToBeizerPath(path: addClosedPathForPoints(points: topPoints), color: color, gradientPoints: topGradientPoints)
// Left
let leftPoints = [topLeftO, topLeftI, bottomLeftI, bottomLeftO, topLeftO]
let leftGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0)]
addGradientToBeizerPath(path: addClosedPathForPoints(points: leftPoints), color: color, gradientPoints: leftGradientPoints)
// Right
let rightPoints = [topRightO, topRightI, bottomRightI, bottomRightO, topRightO]
let rightGradientPoints = [CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 0)]
addGradientToBeizerPath(path: addClosedPathForPoints(points: rightPoints), color: color, gradientPoints: rightGradientPoints)
// Bottom
let bottomPoints = [bottomLeftO, bottomLeftI, bottomRightI, bottomRightO, bottomLeftO]
let bottomGradientPoints = [CGPoint(x: 0, y: 1), CGPoint(x: 0, y: 0)]
addGradientToBeizerPath(path: addClosedPathForPoints(points: bottomPoints), color: color, gradientPoints: bottomGradientPoints)
}
func addClosedPathForPoints(points: [CGPoint]) -> UIBezierPath? {
guard points.count == 5 else { return nil }
let path = UIBezierPath()
path.move(to: points[0])
path.addLine(to: points[1])
path.addLine(to: points[2])
path.addLine(to: points[3])
path.addLine(to: points[4])
path.close()
return path
}
func addGradientToBeizerPath(path: UIBezierPath?, color: UIColor, gradientPoints: [CGPoint]) {
guard let path = path, gradientPoints.count == 2 else { return }
let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [color.cgColor, UIColor.clear.cgColor]
gradient.startPoint = gradientPoints[0]
gradient.endPoint = gradientPoints[1]
// let shapeMask = CAShapeLayer()
// shapeMask.path = path.cgPath
// gradient.mask = shapeMask
self.layer.insertSublayer(gradient, at: 0)
}
}
You will notice that the edges do not look that great.To fix that, I am giving the edges an angle. When I apply a mask to this gradient with this angle, the right and bottom paths disappear like this:
All I am doing here is using some closed bezierPaths and applying a gradient to them. If the gradient has a mask (the commented code is uncommented), two of the paths disappear. I have a feeling that I am not understanding something so hopefully someone here can tell me how to use CAShapeLayer properly.
This comment to CALayer mask property
explains it perfectly:
The mask layer lives in the masked layer's coordinate system just as if it were a sublayer.
In your case, the origin of the right and bottom gradient layer is not
at (0, 0) of the enclosing view, but at (frame.width - width, 0)
and (frame.height - width, 0) respectively.
On the other hand, the coordinates of the points in
oshapeMask.path are relative to (0, 0) of the enclosing view.
A possible simple fix is to transform the coordinate system of
the shape layer so that it uses the same coordinates as the points
of the given path:
let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.bounds = path.bounds // <<--- ADDED HERE!
gradient.colors = [color.cgColor, UIColor.clear.cgColor]
gradient.startPoint = gradientPoints[0]
gradient.endPoint = gradientPoints[1]
let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath
gradient.mask = shapeMask
self.layer.addSublayer(gradient)
I wanted to make a white color view with a triangle shaped pointer being grooved inside like this:
As shown in the image above, goal is to create a "rounded groove" inset into the whiteview
let pointerRadius:CGFloat = 4
pointerLayer = CAShapeLayer()
pointerLayer.path = pointerPathForContentSize(contentSize: bounds.size).cgPath
pointerLayer.lineJoin = kCALineJoinRound
pointerLayer.lineWidth = 2*pointerRadius
pointerLayer.fillColor = UIColor.white.cgColor
pointerLayer.strokeColor = UIColor.black.cgColor
pointerLayer.backgroundColor = UIColor.white.cgColor
layer.addSublayer(pointerLayer)
But what I get is this:
But,if I set the stroke color to white
pointerLayer.strokeColor = UIColor.white.cgColor
In the groove I wanted to have a rounded edge in bottom (just like in the first pic) which no more remains visible when fillColor and strokeColor get matched (both white).
How can I fix it?
Is there any other way to achieve this?
Here is the code for pointer path:
private func pointerPathForContentSize(contentSize: CGSize) -> UIBezierPath
{
let rect = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
let width:CGFloat = 20
let height:CGFloat = 20
let path = UIBezierPath()
let startX:CGFloat = 50
let startY:CGFloat = rect.minY
path.move(to: CGPoint(x: startX , y: startY))
path.addLine(to: CGPoint(x: (startX + width*0.5), y: startY + height))
path.addLine(to: CGPoint(x: (startX + width), y: startY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
path.close()
return path
}
Since you have already outlined the shape you want by stroking the path, I think the simplest solution is probably to use the stroked and filled path as a mask.
For example, here is a rectangular red view:
And here is the same red view with the notch cut out of the top. This seems to be the sort of thing you're after:
What I did there was to mask the red view with a special mask view that draws the notch using .clear blend mode:
class MaskView : UIView {
override init(frame: CGRect) {
super.init(frame:frame)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let con = UIGraphicsGetCurrentContext()!
con.fill(self.bounds)
con.setBlendMode(.clear)
con.move(to: CGPoint(x:0, y:-4))
con.addLine(to: CGPoint(x:100, y:-4))
con.addLine(to: CGPoint(x:110, y:15))
con.addLine(to: CGPoint(x:120, y:-4))
con.addLine(to: CGPoint(x: self.bounds.maxX, y:-4))
con.addLine(to: CGPoint(x: self.bounds.maxX, y:-20))
con.addLine(to: CGPoint(x: 0, y:-20))
con.closePath()
con.setLineJoin(.round)
con.setLineWidth(10)
con.drawPath(using: .fillStroke) // stroke it and fill it
}
}
So then when I'm ready to cut out the notch on the red view, I just say:
self.redView.mask = MaskView(frame:self.redView.bounds)
I am wondering how I would go about implementing a wave-like border of a UIView. Is this possible through UIView's alone? Or would creating this appearance through a UIImageView be the way to go?
An example might be something similar to:
Thanks for your help!
Here is a code based solution that doesn't require any images. This creates a custom view using UIBezierPath to create the sine waves.
import UIKit
class WavyView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
return nil // TODO
}
override func draw(_ rect: CGRect) {
// Fill the whole background with the darkest blue color
UIColor(red: 0.329, green: 0.718, blue: 0.875, alpha: 1).set()
let bg = UIBezierPath(rect: rect)
bg.fill()
// Add the first sine wave filled with a very transparent white
let top1: CGFloat = 17.0
let wave1 = wavyPath(rect: CGRect(x: 0, y: top1, width: frame.width, height: frame.height - top1), periods: 1.5, amplitude: 21, start: 0.55)
UIColor(white: 1.0, alpha: 0.1).set()
wave1.fill()
// Add the second sine wave over the first
let top2: CGFloat = 34.0
let wave2 = wavyPath(rect: CGRect(x: 0, y: top2, width: frame.width, height: frame.height - top2), periods: 1.5, amplitude: 21, start: 0.9)
UIColor(white: 1.0, alpha: 0.15).set()
wave2.fill()
// Add the text
let paraAttrs = NSMutableParagraphStyle()
paraAttrs.alignment = .center
let textRect = CGRect(x: 0, y: frame.maxY - 64, width: frame.width, height: 24)
let textAttrs = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20), NSForegroundColorAttributeName: UIColor(white: 1.0, alpha: 0.9), NSParagraphStyleAttributeName: paraAttrs]
("New user? Register here." as NSString).draw(in: textRect, withAttributes: textAttrs)
}
// This creates the desired sine wave bezier path
// rect is the area to fill with the sine wave
// periods is how may sine waves fit across the width of the frame
// amplitude is the height in points of the sine wave
// start is an offset in wavelengths for the left side of the sine wave
func wavyPath(rect: CGRect, periods: Double, amplitude: Double, start: Double) -> UIBezierPath {
let path = UIBezierPath()
// start in the bottom left corner
path.move(to: CGPoint(x: rect.minX, y: rect.maxY))
let radsPerPoint = Double(rect.width) / periods / 2.0 / Double.pi
let radOffset = start * 2 * Double.pi
let xOffset = Double(rect.minX)
let yOffset = Double(rect.minY) + amplitude
// This loops through the width of the frame and calculates and draws each point along the size wave
// Adjust the "by" value as needed. A smaller value gives smoother curve but takes longer to draw. A larger value is quicker but gives a rougher curve.
for x in stride(from: 0, to: Double(rect.width), by: 6) {
let rad = Double(x) / radsPerPoint + radOffset
let y = sin(rad) * amplitude
path.addLine(to: CGPoint(x: x + xOffset, y: y + yOffset))
}
// Add the last point on the sine wave at the right edge
let rad = Double(rect.width) / radsPerPoint + radOffset
let y = sin(rad) * amplitude
path.addLine(to: CGPoint(x: Double(rect.maxX), y: y + yOffset))
// Add line from the end of the sine wave to the bottom right corner
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
// Close the path
path.close()
return path
}
}
// This creates the view with the same size as the image posted in the question
let wavy = WavyView(frame: CGRect(x: 0, y: 0, width: 502, height: 172))
The result of running this code in a Swift playground gives the following:
Obviously you can adjust any of the values in the code above to tweak the result.
The easiest approach would be to use a UIImageView. However, it is also possible by creating a custom border for the UIView but that will require a lot of code to draw the shapes.