How do I create a circle with CALayer? - swift

I have the code below tested, but when I give it constraints it becomes a little small circle:
override func drawRect(rect: CGRect) {
var path = UIBezierPath(ovalInRect: rect)
fillColor.setFill()
path.fill()
//set up the width and height variables
//for the horizontal stroke
let plusHeight:CGFloat = 300.0
let plusWidth:CGFloat = 450.0
//create the path
var plusPath = UIBezierPath()
//set the path's line width to the height of the stroke
plusPath.lineWidth = plusHeight
//move the initial point of the path
//to the start of the horizontal stroke
plusPath.moveToPoint(CGPoint(
x:self.bounds.width/2 - plusWidth/2 + 0.5,
y:self.bounds.height/2 + 0.5))
//add a point to the path at the end of the stroke
plusPath.addLineToPoint(CGPoint(
x:self.bounds.width/2 + plusWidth/2 + 0.5,
y:self.bounds.height/2 + 0.5))
}

Change radius and fillColor as you want. :)
import Foundation
import UIKit
class CircleLayerView: UIView {
var circleLayer: CAShapeLayer!
override func draw(_ rect: CGRect) {
super.draw(rect)
if circleLayer == nil {
circleLayer = CAShapeLayer()
let radius: CGFloat = 150.0
circleLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2.0 * radius, height: 2.0 * radius), cornerRadius: radius).cgPath
circleLayer.position = CGPoint(x: self.frame.midX - radius, y: self.frame.midY - radius)
circleLayer.fillColor = UIColor.blue.cgColor
self.layer.addSublayer(circleLayer)
}
}
}

The rect being passed into drawRect is the area that needs to be updated, not the size of the drawing. In your case, you would probably just ignore the rect being passed in and set the circle to the size you want.
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 300, 300))
UIColor.whiteColor().setFill()
ovalPath.fill()

The only correct way to do it:
private lazy var whiteCoin: CAShapeLayer = {
let c = CAShapeLayer()
c.path = UIBezierPath(ovalIn: bounds).cgPath
c.fillColor = UIColor.white.cgColor
layer.addSublayer(c)
return c
}()
That literally makes a layer, as you wanted.
In iOS you must correctly resize any layers you are in charge of, when the view is resized/redrawn.
How do you do that? It is the very raison d'etre of layoutSubviews.
class ProperExample: UIView {
open override func layoutSubviews() {
super.layoutSubviews()
whiteCoin.frame = bounds
}
}
It's that simple.
class ProperExample: UIView {
open override func layoutSubviews() {
super.layoutSubviews()
whiteCoin.frame = bounds
}
private lazy var whiteCoin: CAShapeLayer = {
let c = CAShapeLayer()
c.path = UIBezierPath(ovalIn: bounds).cgPath
c.fillColor = UIColor.white.cgColor
layer.addSublayer(c)
return c
}()
}

Related

can't make round corners for UIView

I have a UIView object inside a horizontal stackView.
I'm calling this function inside LayoutSubviews:
func roundCorners(corners: UIRectCorner, radius: CurveRadius) {
var r = CGFloat()
switch radius {
case .small:
r = self.frame.width / 30
case .medium:
r = self.frame.width / 25
}
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: r, height: r))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
but it just doesn't work. I guess it has something to do with a stackView. can anyone help me out?
extension UIView {
/// Rounds ``UIView`` corners.
/// - Parameters:
/// - maskedCorners: Corners to be rounded.
/// - cornerRadius: Value to be set as corner radius.
func roundCorners(maskedCorners: CACornerMask,
cornerRadius: CGFloat) {
layer.cornerRadius = cornerRadius
layer.maskedCorners = maskedCorners
layer.masksToBounds = true
}
}
I'm not sure if the UIStackView is the problem here, but there's another, more re-usable way to do this using a CACornerMask on the UIView's layer in an extension:
extension UIView {
func roundCorners() {
self.layer.cornerRadius = 10
self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
}
}
When you create your view, just call the roundCorners(), like this:
private lazy var roundCorneredView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = .red
view.roundCorners()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
Then add that view to your hierarchy in the usual way using addSubview.
CACornerMask docs # Apple

Custom shape to UISlider and update progress in Swift 5

I have checked some of the StackOverflow answers regarding custom UIView slider but using them I unable to make the slider like this. This makes a circle or half circle. I have figured out some library that makes circle slider using UIView but its not helpful to me so could anyone please help me out. How can I make slider like in below UIImage? Thanks!
You will probably just roll your own. (You obviously could search for third party implementations, but that would be out of scope for StackOverflow.) There are a lot of ways of tackling this, but the basic elements here are:
The pink arc for the overall path. Personally, I'd use a CAShapeLayer for that.
The white arc from the start to the current progress (measured from 0 to 1). Again, a CAShapeLayer would be logical.
The white dot placed at the spot of the current progress. Below I create a CALayer with white background and then apply a CAGradientLayer as a mask to that. You could also just create a UIImage for this.
In terms of how to set the progress, you would set the paths of the pink and white arcs to the same path, but just update the strokeEnd of the white arc. You would also adjust the position of the white dot layer accordingly.
The only complicated thing here is figuring out the center of the arc. In my example below, I calculate it with some trigonometry based upon the bounds of the view so that arc goes from lower left corner, to the top, and back down the the lower right corner. Or you might instead pass the center of the arc as a parameter.
Anyway, it might look like:
#IBDesignable
class ArcView: UIView {
#IBInspectable
var lineWidth: CGFloat = 7 { didSet { updatePaths() } }
#IBInspectable
var progress: CGFloat = 0 { didSet { updatePaths() } }
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
progress = 0.35
}
lazy var currentPositionDotLayer: CALayer = {
let layer = CALayer()
layer.backgroundColor = UIColor.white.cgColor
let rect = CGRect(x: 0, y: 0, width: lineWidth * 3, height: lineWidth * 3)
layer.frame = rect
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
gradientLayer.type = .radial
gradientLayer.frame = rect
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.locations = [0.5, 1]
layer.mask = gradientLayer
return layer
}()
lazy var progressShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineCap = .round
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
return shapeLayer
}()
lazy var totalShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineCap = .round
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = #colorLiteral(red: 0.9439327121, green: 0.5454334617, blue: 0.6426400542, alpha: 1)
return shapeLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
updatePaths()
}
}
// MARK: - Private utility methods
private extension ArcView {
func configure() {
layer.addSublayer(totalShapeLayer)
layer.addSublayer(progressShapeLayer)
layer.addSublayer(currentPositionDotLayer)
}
func updatePaths() {
let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
let halfWidth = rect.width / 2
let height = rect.height
let theta = atan(halfWidth / height)
let radius = sqrt(halfWidth * halfWidth + height * height) / 2 / cos(theta)
let center = CGPoint(x: rect.midX, y: rect.minY + radius)
let delta = (.pi / 2 - theta) * 2
let startAngle = .pi * 3 / 2 - delta
let endAngle = .pi * 3 / 2 + delta
let path = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
progressShapeLayer.path = path.cgPath // white arc
totalShapeLayer.path = path.cgPath // pink arc
progressShapeLayer.strokeEnd = progress
let currentAngle = (endAngle - startAngle) * progress + startAngle
let dotCenter = CGPoint(x: center.x + radius * cos(currentAngle),
y: center.y + radius * sin(currentAngle))
currentPositionDotLayer.position = dotCenter
}
}
Above, I set the background color of the ArcView so you could see its bounds, but you would obviously set the background color to be transparent.
Now there are tons of additional features you might add (e.g. add user interaction so you could “scrub” it, etc.). See https://github.com/robertmryan/ArcView for example. But the key when designing this sort of stuff is to just break it down into its constituent elements, layering one on top of the other.
You can programmatically set the progress of the arcView to get it to change the current value between values of 0 and 1:
func startUpdating() {
arcView.progress = 0
var current = 0
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [weak self] timer in
current += 1
guard let self = self, current <= 10 else {
timer.invalidate()
return
}
self.arcView.progress = CGFloat(current) / 10
}
}
Resulting in:

Using SwiftUI or UIKit to position view elements?

This is more or less a repost of a question that I think could have been reproduced more minimally. I'm trying to form a text bubble using the triangle created by the overriden draw() function and the rest of the callout. I removed all the code that couldn't possibly affect the positioning of either the triangle or the box.
Recap: I'd like to move the triangle created by the draw function outside of the frame created in the initialization (Currently, it's inside the frame).
If I can add anything to clarify or make this question better, let me know.
class CustomCalloutView: UIView, MGLCalloutView {
let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true
let tipHeight: CGFloat = 10.0
let tipWidth: CGFloat = 20.0
lazy var leftAccessoryView = UIView()
lazy var rightAccessoryView = UIView()
weak var delegate: MGLCalloutViewDelegate?
//MARK: Subviews -
required init() {
// init with 75% of width and 120px tall
super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width:
UIScreen.main.bounds.width * 0.75, height: 120)))
setup()
}
override var center: CGPoint {
set {
var newCenter = newValue
newCenter.y -= bounds.midY
super.center = newCenter
}
get {
return super.center
}
}
func setup() {
// setup this view's properties
self.backgroundColor = UIColor.white
}
func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect,
animated: Bool) {
//Always, Slightly above center
self.center = view.center.applying(CGAffineTransform(translationX: 0, y: -self.frame.height))
view.addSubview(self)
}
override func draw(_ rect: CGRect) {
// Draw the pointed tip at the bottom.
let fillColor: UIColor = .black
let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0)
let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0), y: rect.origin.y +
rect.size.height)
let heightWithoutTip = rect.size.height - tipHeight - 1
let currentContext = UIGraphicsGetCurrentContext()!
let tipPath = CGMutablePath()
tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip))
tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y))
tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip))
tipPath.closeSubpath()
fillColor.setFill()
currentContext.addPath(tipPath)
currentContext.fillPath()
}
}

Why are these CAShapeLayers not going where expected?

I'm working on a custom loading indicator and am having a lot of issues with CAShapeLayers.
The loading indicator will be contained within a custom UIView so that any viewController can use it.
First issue:
The frame of the subview is not matching the bounds.
When using this code to display a circle in each corner of the frame the circles are placed in a square shape but it is no where near the view.
import UIKit
View Controller:
class MergingCicles: UIViewController, HolderViewDelegate {
func animateLabel() {
}
var holderView = HolderView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addHolderView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addHolderView() {
let boxSize: CGFloat = 100.0
holderView.frame = CGRect(x: view.bounds.width / 2 - boxSize / 2,
y: view.bounds.height / 2 - boxSize / 2,
width: boxSize,
height: boxSize)
holderView.parentFrame = view.frame
holderView.delegate = self
holderView.center = self.view.center
view.addSubview(holderView)
holderView.addCircleLayer()
}
}
Subview:
Import UIKit
protocol HolderViewDelegate:class {
func animateLabel()
}
class HolderView: UIView {
let initalLayer = InitialLayer()
let triangleLayer = TriangleLayer()
let redRectangleLayer = RectangleLayer()
let blueRectangleLayer = RectangleLayer()
let arcLayer = ArcLayer()
var parentFrame :CGRect = CGRect.zero
weak var delegate:HolderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
func addCircleLayer() {
var circleLocations = [CGPoint]()
let offset = CircleLayer().maxSize / 2
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.maxY - offset))
circleLocations.append(CGPoint(x: self.frame.minX + offset, y: self.frame.minY + offset))
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.minY + offset))
circleLocations.append(CGPoint(x: self.frame.minX + offset, y: self.frame.maxY - offset))
circleLocations.append(layer.anchorPoint)
for point in circleLocations {
let circle = CircleLayer()
circle.updateLocation(Size: .medium, center: point)
self.layer.addSublayer(circle)
}
self.backgroundColor = .blue
// layer.anchorPoint = CGPoint(x: (self.bounds.maxX + self.bounds.maxX)/2, y: (self.bounds.maxY + self.bounds.minY)/2)
let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(Double.pi * 2)
rotationAnimation.duration = 0.45
rotationAnimation.isCumulative = true
//rotationAnimation.repeatCount = 1000
//rotationAnimation.isRemovedOnCompletion = true
// layer.add(rotationAnimation, forKey: nil)
}
}
Circle Layer:
import Foundation
import UIKit
enum ShapeSize {
case medium
case small
case large
}
class CircleLayer: CAShapeLayer {
let animationDuration: CFTimeInterval = 0.3
let maxSize = CGFloat(50)
override init() {
super.init()
fillColor = UIColor.red.cgColor
}
func updateLocation(Size: ShapeSize, center: CGPoint){
switch Size {
case .medium:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: maxSize/3, height: maxSize/3)).cgPath
case .small:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: (2*maxSize)/3, height: (2*maxSize)/3)).cgPath
case .large:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: maxSize, height: maxSize)).cgPath
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Result:
This really shows that the frame is no where near the uiView.
If I change addCircleLayer to use bounds instead I get something much closer:
But still the circles are not in the corners (except the bottom right one, that one is correct). It appears there is some extra space on the left and top of the view that is not captured using self.bounds.
The ultimate goal is to also rotate the circles 360 degrees around the center but as shown by the circle in the upper left corner the layer anchor is not in the center of the view, I changed the anchor to be the center of the circles but then nothing appeared on screen at all.
You're saying things like
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.maxY - offset))
But self.frame is where the view is located in its own superview. Thus, the shape layer ends up offset from the view by as much as the view is offset from its own superview. Wherever you say frame here, you mean bounds.
I found the problem was then when drawing the circles I was using UIBezierPath(ovalIn:CGRect, width: CGFloat, height: CGFloat which was using the x value for the left side of the circle. When I changed to UIBezierPath(arcCenter: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) the point was used for the center of the circle and made it all fit where expected when using self.bounds to calculate the points.
After that I no longer had to change the anchor point as it was in the correct location by default.
I didn't figure out why the frame is in a completely different spot but it is no longer impacting the project.

How to change color of Triangle figure using drawRect on Swift

I have made triangle view, called UpTriangleView. It is used in order to show vote. When they are tapped, I want to change their color. I wanna UIColor.grayColor().setStroke() from instance, however I have no idea how to do it. Please tell me how to do it, if you know. Thank you for your kindeness.
class UpTriangleView: UIView {
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.clearColor()
// Get Height and Width
let layerHeight = self.layer.frame.height
let layerWidth = self.layer.frame.width
// Create Path
let line = UIBezierPath()
// Draw Points
line.moveToPoint(CGPointMake(0, layerHeight))
line.addLineToPoint(CGPointMake(layerWidth, layerHeight))
line.addLineToPoint(CGPointMake(layerWidth/2, 0))
line.addLineToPoint(CGPointMake(0, layerHeight))
line.closePath()
// Apply Color
UIColor.grayColor().setStroke()
UIColor.grayColor().setFill()
line.lineWidth = 3.0
line.fill()
line.stroke()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = line.CGPath
self.layer.mask = shapeLayer
}
}
class QATableViewCell : UITableViewCell{
#IBOutlet weak var upTriangleView: UpTriangleView!
}
Add a property to your UpTriangleView that is the color you want to draw it. Implement didSet and call setNeedsDisplay() if the color is set:
class UpTriangleView: UIView {
var color = UIColor.gray {
didSet {
self.setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
self.backgroundColor = .clear
// Get Height and Width
let layerHeight = self.layer.bounds.height
let layerWidth = self.layer.bounds.width
// Create Path
let line = UIBezierPath()
// Draw Points
line.move(to: CGPoint(x: 0, y: layerHeight))
line.addLine(to: CGPoint(x: layerWidth, y: layerHeight))
line.addLine(to: CGPoint(x: layerWidth/2, y: 0))
line.addLine(to: CGPoint(x: 0, y: layerHeight))
line.close()
// Apply Color
color.setStroke()
color.setFill()
line.lineWidth = 3.0
line.fill()
line.stroke()
// Mask to Path
let shapeLayer = CAShapeLayer()
shapeLayer.path = line.cgPath
self.layer.mask = shapeLayer
}
}
Now, demo it in a Playground (see picture below for results):
let utv = UpTriangleView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
utv.color = .yellow // now triangle is yellow
utv.color = .red // now triangle is red
setNeedsDisplay will tell iOS your view needs redrawing, and drawRect will be called again using the newly set color.