Drawing sublayers inside a bezier Arc - ios

I'm trying to draw a series of vertical lines inside of an arc but I'm having trouble being able to do this. I'm trying to do this using CAShapeLayers The end result is something that looks like this.
I know how to draw the curved arc and the line segments using CAShapeLayers but what I can't seem to figure out is how to draw the vertical lines inside the CAShapeLayer
My initial approach is to subclass CAShapeLayer and in the subclass, attempt to draw the vertical lines. However, I'm not getting the desired results. Here is my code for adding a line to a bezier point and attempting to add the sub layers.
class CustomLayer : CAShapeLayer {
override init() {
super.init()
}
func drawDividerLayer(){
print("Init has been called in custom layer")
print("The bounds of the custom layer is: \(bounds)")
print("The frame of the custom layer is: \(frame)")
let bezierPath = UIBezierPath()
let dividerShapeLayer = CAShapeLayer()
dividerShapeLayer.strokeColor = UIColor.redColor().CGColor
dividerShapeLayer.lineWidth = 1
let startPoint = CGPointMake(5, 0)
let endPoint = CGPointMake(5, 8)
let convertedStart = convertPoint(startPoint, toLayer: dividerShapeLayer)
let convertedEndPoint = convertPoint(endPoint, toLayer: dividerShapeLayer)
bezierPath.moveToPoint(convertedStart)
bezierPath.addLineToPoint(convertedEndPoint)
dividerShapeLayer.path = bezierPath.CGPath
addSublayer(dividerShapeLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class DrawView : UIView {
var customDrawLayer : CAShapeLayer!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//drawLayers()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
func drawLayers() {
let bezierPath = UIBezierPath()
let startPoint = CGPointMake(5, 35)
let endPoint = CGPointMake(100, 35)
bezierPath.moveToPoint(startPoint)
bezierPath.addLineToPoint(endPoint)
let customLayer = CustomLayer()
customLayer.frame = CGPathGetBoundingBox(bezierPath.CGPath)
customLayer.drawDividerLayer()
customLayer.strokeColor = UIColor.blackColor().CGColor
customLayer.opacity = 0.5
customLayer.lineWidth = 8
customLayer.fillColor = UIColor.clearColor().CGColor
layer.addSublayer(customLayer)
customLayer.path = bezierPath.CGPath
}
However this code produces this image:
It definitely seems that I have a coordinate space problem/bounds/frame issue but I'm not quite sure. The way I want this to work is to draw from the top of the superLayer to the bottom of the superLayer inside of the CustomLayer class. But not only that, this must work using the bezier path addArcWithCenter: method which I haven't gotten to yet because I'm trying to solve this problem first. Any help would be appreciated.

The easiest way to draw an arc that consists of lines is to use lineDashPattern:
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)
let arc = CAShapeLayer()
arc.path = path.CGPath
arc.lineWidth = 50
arc.lineDashPattern = [4,15]
arc.strokeColor = UIColor.lightGrayColor().CGColor
arc.fillColor = UIColor.clearColor().CGColor
view.layer.addSublayer(arc)
So this is a blue arc underneath the dashed arc shown above. Obviously, I enlarged it for the sake of visibility, but it illustrates the idea.

Related

CGContext Drawing two adjacent rhomboids produce a very thin gap, how to reduce it?

The two adjacent rectangle is ok as image below.
override func draw(_ rect: CGRect) {
// Drawing code
let leftTop = CGPoint(x:50,y:50)
let rightTop = CGPoint(x:150,y:100)
let leftMiddle = CGPoint(x:50,y:300)
let rightMiddle = CGPoint(x:150,y:300)
let leftDown = CGPoint(x:50,y:600)
let rightDown = CGPoint(x:150,y:650)
let context = UIGraphicsGetCurrentContext()
context?.addLines(between: [leftTop,rightTop,rightMiddle,leftMiddle])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle,rightMiddle,rightDown,leftDown])
context?.fillPath()
let leftTop1 = CGPoint(x:200,y:50)
let rightTop1 = CGPoint(x:300,y:100)
let leftMiddle1 = CGPoint(x:200,y:300)
let rightMiddle1 = CGPoint(x:300,y:350)
let leftDown1 = CGPoint(x:200,y:600)
let rightDown1 = CGPoint(x:300,y:650)
context?.addLines(between: [leftTop1,rightTop1,rightMiddle1,leftMiddle1])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle1,rightMiddle1,rightDown1,leftDown1])
context?.fillPath()
}
You may need to zoom in to see the gap. If I draw a thin line to cover the gap, then any width may overlap if the color has an alpha channel.
Change shapeColor to let shapeColor = UIColor(white: 0.0, alpha: 0.5) and add context?.setShouldAntialias(false)
I have the same result using the CGContext even if I use setShouldAntialias(true) or if I try to call strokePath() on the context. But it works fine with sublayers, CGPath and strokeColor
class RhombView: UIView {
let shapeColor: UIColor = .black
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
func setupView() {
let leftTop1 = CGPoint(x:200.0,y:50.0)
let rightTop1 = CGPoint(x:300.0,y:100.0)
let leftMiddle1 = CGPoint(x:200.0,y:300.0)
let rightMiddle1 = CGPoint(x:300.0,y:350.0)
let leftDown1 = CGPoint(x:200.0,y:600.0)
let rightDown1 = CGPoint(x:300.0,y:650.0)
var path = UIBezierPath()
path.move(to: leftTop1)
path.addLine(to: rightTop1)
path.addLine(to: rightMiddle1)
path.addLine(to: leftMiddle1)
path.close()
let subLayer1 = CAShapeLayer()
subLayer1.path = path.cgPath
subLayer1.frame = self.layer.frame
subLayer1.fillColor = shapeColor.cgColor
subLayer1.strokeColor = shapeColor.cgColor
self.layer.addSublayer(subLayer1)
path = UIBezierPath()
path.move(to: leftMiddle1)
path.addLine(to: rightMiddle1)
path.addLine(to: rightDown1)
path.addLine(to: leftDown1)
path.close()
let subLayer2 = CAShapeLayer()
subLayer2.path = path.cgPath
subLayer2.frame = self.layer.frame
subLayer2.fillColor = shapeColor.cgColor
subLayer2.strokeColor = shapeColor.cgColor
self.layer.addSublayer(subLayer2)
self.layer.backgroundColor = UIColor.white.cgColor
}
}
If you remove both subLayer.strokeColor you will see the gap.
This is related to screen resolution. On devices with high resolution one point actually has 2 or 3 pixels. That's why to draw an inclined line iOS draws some edge pixels with some opacity, when 2 lines are next to each other these edge pixels overlap. In your case I was able to fix the issue by making the following change
let leftTop1 = CGPoint(x:200,y:50)
let rightTop1 = CGPoint(x:300,y:100)
let leftMiddle1 = CGPoint(x:200,y:300)
let rightMiddle1 = CGPoint(x:300,y:350)
let leftMiddle2 = CGPoint(x:200,y:300.333)
let rightMiddle2 = CGPoint(x:300,y:350.333)
let leftDown1 = CGPoint(x:200,y:600)
let rightDown1 = CGPoint(x:300,y:650)
context?.addLines(between: [leftTop1,rightTop1,rightMiddle1,leftMiddle1])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle2,rightMiddle2,rightDown1,leftDown1])
context?.fillPath()
Basically moving down the second rhomboid by 1 pixel (1/3 = 0.333...), I have tested on a screen with 1:3 pixel density, for the solution to work on all devices you'll need to check the scaleFactor of the screen.

iOS: Animating a circle slice into a wider one

Core-Animation treats angles as described in this image:
(image from http://btk.tillnagel.com/tutorials/rotation-translation-matrix.html)
EDIT: Adding an animated gif to explain better what I'm needing:
I need to animate a slice to grow wider, starting at 300:315 degrees, and ending 300:060.
To create each slice I'm using this function:
extension CGFloat {
func toRadians() -> CGFloat {
return self * CGFloat(Double.pi) / 180.0
}
}
func createSlice(angle1:CGFloat, angle2:CGFloat) -> UIBezierPath! {
let path: UIBezierPath = UIBezierPath()
let width: CGFloat = self.frame.size.width/2
let height: CGFloat = self.frame.size.height/2
let centerToOrigin: CGFloat = sqrt((height)*(height)+(width)*(width));
let ctr: CGPoint = CGPoint(x: width, y: height)
path.move(to: ctr)
path.addArc( withCenter: ctr,
radius: centerToOrigin,
startAngle: CGFloat(angle1).toRadians(),
endAngle: CGFloat(angle2).toRadians(),
clockwise: true
)
path.close()
return path
}
I can now create the two slices and a sublayer with the smaller one, but I can't find how to proceed from this point:
func doStuff() {
path1 = self.createSlice(angle1: 300,angle2: 315)
path2 = self.createSlice(angle1: 300,angle2: 60)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path1.cgPath
shapeLayer.fillColor = UIColor.cyan.cgColor
self.layer.addSublayer(shapeLayer)
I would highly appreciate any help here!
Only a single color
If you want to animate the angle of a solid color filled pie segment like the one in your question, then you can do it by animating the strokeEnd of a CAShapeLayer.
The "trick" here is to make a very wide line. More specifically, you can create a path that is just an arc (the dashed line in the animation below) at half of the intended radius and then giving it the full radius as its line width. When you animate stroking that line it looks like the orange segment below:
Depending on your use case, you can either:
create a path from one angle to the other angle and animate stroke end from 0 to 1
create a path for a full circle, set stroke start and stroke end to some fraction of the circle, and animate stroke end from the start fraction to the end fraction.
If your drawing is just a single color like this, then this will be the smallest solution to your problem.
However, if your drawing is more complex (e.g. also stroking the pie segment) then this solutions simply won't work and you'll have to do something more complex.
Custom drawing / Custom animations
If your drawing of the pie segment is any more complex, then you'll quickly find yourself having to create a layer subclass with custom animatable properties. Doing so is a bit more code - some of which might look a bit unusual1 - but not as scary as it might sound.
This might be one of those things that is still more convenient to do in Objective-C.
Dynamic properties
First, create a layer subclass with the properties you're going to need. In Objective-C parlance these properties should be #dynamic, i.e. not synthesized. This isn't the same as dynamic in Swift. Instead we have to use #NSManaged.
class PieSegmentLayer : CALayer {
#NSManaged var startAngle, endAngle, strokeWidth: CGFloat
#NSManaged var fillColor, strokeColor: UIColor?
// More to come here ...
}
This allows Core Animation to handle these properties dynamically allowing it to track changes and integrate them into the animation system.
Note: a good rule of thumb is that these properties should all be related to drawing / visual presentation of the layer. If they aren't then it's quite likely that they don't belong on the layer. Instead they could be added to a view that in turn uses the layer for its drawing.
Copying layers
During the custom animation, Core Animation is going to want to create and render different layer configurations for different frames. Unlike most of Apple's other frameworks, this happens using the copy constructor init(layer:). For the above five properties to be copied along, we need to override init(layer:) and copy over their values.
In Swift we also have to override the plain init() and init?(coder).
override init(layer: Any) {
super.init(layer: layer)
guard let other = layer as? PieSegmentLayer else { return }
fillColor = other.fillColor
strokeColor = other.strokeColor
startAngle = other.startAngle
endAngle = other.endAngle
strokeWidth = other.strokeWidth
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
return nil
}
Reacting to change
Core Animation is in many ways built for performance. One of the ways it achieves this is by avoiding unnecessary work. By default, a layer won't redraw itself when a property changes. But these properties is used for drawing, and we want the layer to redraw when any of them changes. To do that, we need to override needsDisplay(forKey:) and return true if the key was one of these properties.
override class func needsDisplay(forKey key: String) -> Bool {
switch key {
case #keyPath(startAngle), #keyPath(endAngle),
#keyPath(strokeWidth),
#keyPath(fillColor), #keyPath(strokeColor):
return true
default:
return super.needsDisplay(forKey: key)
}
}
Additionally, If we want the layers default implicit animations for these properties, we need to override action(forKey:) to return a partially configured animation object. If we only want some properties (e.g. the angles) to implicitly animate, then we only need to return an animation for those properties. Unless we need something very custom, it's good to just return a basic animation with the fromValue set to the current presentation value:
override func action(forKey key: String) -> CAAction? {
switch key {
case #keyPath(startAngle), #keyPath(endAngle):
let anim = CABasicAnimation(keyPath: key)
anim.fromValue = presentation()?.value(forKeyPath: key)
return anim
default:
return super.action(forKey: key)
}
}
Drawing
The last piece of a custom animation is the custom drawing. This is done by overriding draw(in:) and using the supplied context to draw the layer:
override func draw(in ctx: CGContext) {
let center = CGPoint(x: bounds.midX, y: bounds.midY)
// subtract half the stroke width to avoid clipping the stroke
let radius = min(center.x, center.y) - strokeWidth / 2
// The two angle properties are in degrees but CG wants them in radians.
let start = startAngle * .pi / 180
let end = endAngle * .pi / 180
ctx.beginPath()
ctx.move(to: center)
ctx.addLine(to: CGPoint(x: center.x + radius * cos(start),
y: center.y + radius * sin(start)))
ctx.addArc(center: center, radius: radius,
startAngle: start, endAngle: end,
clockwise: start > end)
ctx.closePath()
// Configure the graphics context
if let fillCGColor = fillColor?.cgColor {
ctx.setFillColor(fillCGColor)
}
if let strokeCGColor = strokeColor?.cgColor {
ctx.setStrokeColor(strokeCGColor)
}
ctx.setLineWidth(strokeWidth)
ctx.setLineCap(.round)
ctx.setLineJoin(.round)
// Draw
ctx.drawPath(using: .fillStroke)
}
Here I've filled and stroked a pie segment that extends from the center of the layer to the nearest edge. You should replace this with your custom drawing.
A custom animation in action
With all that code in place, we now have a custom layer subclass whose properties can be animated both implicitly (just by changing them) and explicitly (by adding a CAAnimation for their key). The results looks something like this:
Final words
It might not be obvious with the frame rate of those animations but one strong benefit from leveraging Core Animation (in different ways) in both these solutions is that it decouples the drawing of a single state from the timing of an animations.
That means that the layer doesn't know and doesn't have to know about the duration, delays, timing curves, etc. These can all be configured and controlled externally.
So at last I have found a solution. It took me time to understand that there is indeed no way to animate the fill of the shape, but we can trick CA engine by creating a filled circle by making the stroke (i.e. the border of the arc) extremely wide, so that it fills the whole circle!
extension CGFloat {
func toRadians() -> CGFloat {
return self * CGFloat(Double.pi) / 180.0
}
}
import UIKit
class SliceView: UIView {
let circleLayer = CAShapeLayer()
var fromAngle:CGFloat = 30
var toAngle:CGFloat = 150
var color:UIColor = UIColor.magenta
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(frame:CGRect, fromAngle:CGFloat, toAngle:CGFloat, color:UIColor) {
self.init(frame:frame)
self.fromAngle = fromAngle
self.toAngle = toAngle
self.color = color
}
func setup() {
circleLayer.strokeColor = color.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
layer.addSublayer(circleLayer)
layer.backgroundColor = UIColor.brown.cgColor
}
override func layoutSubviews() {
super.layoutSubviews()
let startAngle:CGFloat = (fromAngle-90).toRadians()
let endAngle:CGFloat = (toAngle-90).toRadians()
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = min(bounds.width, bounds.height) / 4
let path = UIBezierPath(arcCenter: CGPoint(x: 0,y :0), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
circleLayer.position = center
circleLayer.lineWidth = radius*2
circleLayer.path = path.cgPath
}
public func animate() {
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 3.0;
pathAnimation.fromValue = 0.0;
pathAnimation.toValue = 1.0;
circleLayer.add(pathAnimation, forKey: "strokeEndAnimation")
}
}
So, now we can add it into our view controller and run the animation. In my case - I'm bridging it into Objecive-C but you can easily adapt it to swift.
I simply can't believe that in 2017 it was still not possible to find a ready solution for this simple task. It took me days to have that done. I really hope it will help others!
Here is how I'm using my class:
#implementation ViewController
{
SliceView *sv_;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.grayColor;
CGFloat width = 240.0;
CGFloat height = 160.0;
CGRect r = CGRectMake(
self.view.frame.size.width/2 - width/2,
self.view.frame.size.height/2 - height/2,
width, height);
sv_ = [[SliceView alloc] initWithFrame:r fromAngle:150 toAngle:30 color:[UIColor yellowColor] ];
[self.view addSubview:sv_];
}
- (IBAction)pressedGo:(id)sender {
[sv_ animate];
}
I'm adding a slight improvement for David's class. (David - you are welcome to copy into your book-quality answer!)
You can add the following init function:
convenience init(frame:CGRect, startAngle:CGFloat, endAngle:CGFloat, fillColor:UIColor,
strokeColor:UIColor, strokeWidth:CGFloat) {
self.init()
self.frame = frame
self.startAngle = startAngle
self.endAngle = endAngle
self.fillColor = fillColor
self.strokeColor = strokeColor
self.strokeWidth = strokeWidth
}
and then call it like this (Objective-C in my case):
PieSegmentLayer *sliceLayer = [[PieSegmentLayer alloc] initWithFrame:r startAngle:30 endAngle:180 fillColor:[UIColor cyanColor] strokeColor:[UIColor redColor] strokeWidth:4];
[self.view.layer addSublayer:sliceLayer];

Masking CAGradientLayer over CALayers

In my scene I have 2 views: first holds CALayer instances (bars), another hold CAGradientLayer and placed over first one. Picture below describes current state.
But I need this gradient to be applied only to bars (CALayer) of the first view.
I haven't found any relevant information to my problem. Any help appreciated.
You have to apply a mask to the gradient. There are various ways you could approach this problem.
You could create a CAShapeLayer, set the shape layer's path to the shape of the bars, and set the gradient layer's mask to that shape layer.
Or you could get rid of the bar layer and instead use two gradient layers, one for the orange bars and the other for the gray bars. Put both gradient layers in a subview, side-by-side, and set the superview's layer mask to the shape layer. Here's how to do that.
You'll need two gradient layers and a shape layer:
#IBDesignable
class BarGraphView : UIView {
private let orangeGradientLayer = CAGradientLayer()
private let grayGradientLayer = CAGradientLayer()
private let maskLayer = CAShapeLayer()
You'll also need the bar width:
private let barWidth = CGFloat(9)
At initialization time, set up the gradients and add all the sublayers:
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = .black
initGradientLayer(orangeGradientLayer, with: .orange)
initGradientLayer(grayGradientLayer, with: .gray)
maskLayer.strokeColor = nil
maskLayer.fillColor = UIColor.white.cgColor
layer.mask = maskLayer
}
private func initGradientLayer(_ gradientLayer: CAGradientLayer, with color: UIColor) {
gradientLayer.colors = [ color, color, color.withAlphaComponent(0.6), color ].map({ $0.cgColor })
gradientLayer.locations = [ 0.0, 0.5, 0.5, 1.0 ]
layer.addSublayer(gradientLayer)
}
At layout time, set the frames of the gradient layers and set the mask layer's path. This requires a little work because you don't want a bar to be half orange and half gray.
override func layoutSubviews() {
super.layoutSubviews()
let barCount = ceil(bounds.size.width / barWidth)
let orangeBarCount = floor(barCount / 2)
let grayBarCount = barCount - orangeBarCount
var grayFrame = bounds
grayFrame.size.width = grayBarCount * barWidth
grayFrame.origin.x = frame.maxX - grayFrame.size.width
grayGradientLayer.frame = grayFrame
var orangeFrame = bounds
orangeFrame.size.width -= grayFrame.size.width
orangeGradientLayer.frame = orangeFrame
maskLayer.frame = bounds
maskLayer.path = barPath()
}
private func barPath() -> CGPath {
var columnBounds = self.bounds
columnBounds.origin.x = columnBounds.maxX
columnBounds.size.width = barWidth
let path = CGMutablePath()
for datum in barData.reversed() {
columnBounds.origin.x -= barWidth
let barHeight = CGFloat(datum) * columnBounds.size.height
let barRect = columnBounds.insetBy(dx: 1, dy: (columnBounds.size.height - barHeight) / 2)
path.addRoundedRect(in: barRect, cornerWidth: 2, cornerHeight: 2)
}
return path
}
let barData: [Double] = {
let count = 100
return (0 ..< count).map({ 0.5 + (1 + sin(8.0 * .pi * Double($0) / Double(count))) / 4 })
}()
}
Result:
The BarGraphView is transparent wherever there are no bars. If you want it on a dark background, put a dark view behind it, or make it a subview of a dark view:

Adding border with width to UIView show small background outside

I'm trying to add circle border to a UIView with green background, I created simple UIView subclass with borderWidth, cornerRadius and borderColor properties and I'm setting it from storyboard.
#IBDesignable
class RoundedView: UIView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable var borderColor: UIColor {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
} else {
return UIColor.clear
}
}
set {
layer.borderColor = newValue.cgColor
}
}
}
But when I compile and run an app or display it in InterfaceBuilder I can see a line outside the border that is still there (and is quite visible on white background).
This RoundedView with green background, frame 10x10, corner radius = 5 is placed in corner of plain UIImageView (indicates if someone is online or not). You can see green border outside on both UIImageView and white background.
Can you please tell me what's wrong?
What you are doing is relying on the layer to draw your border and round the corners. So you are not in charge of the result. You gave it a green background, and now you are seeing the background "stick out" at the edge of the border. And in any case, rounding the corners is a really skanky and unreliable way to make a round view. To make a round view, make a round mask.
So, the way to make your badge is to take complete charge of what it is drawn: you draw a green circle in the center of a white background, and mask it all with a larger circle to make the border.
Here is a Badge view that will do precisely what you're after, with no artifact round the outside:
class Badge : UIView {
class Mask : UIView {
override init(frame:CGRect) {
super.init(frame:frame)
self.isOpaque = false
self.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let con = UIGraphicsGetCurrentContext()!
con.fillEllipse(in: CGRect(origin:.zero, size:rect.size))
}
}
let innerColor : UIColor
let outerColor : UIColor
let innerRadius : CGFloat
var madeMask = false
init(frame:CGRect, innerColor:UIColor, outerColor:UIColor, innerRadius:CGFloat) {
self.innerColor = innerColor
self.outerColor = outerColor
self.innerRadius = innerRadius
super.init(frame:frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let con = UIGraphicsGetCurrentContext()!
con.setFillColor(outerColor.cgColor)
con.fill(rect)
con.setFillColor(innerColor.cgColor)
con.fillEllipse(in: CGRect(
x: rect.midX-innerRadius, y: rect.midY-innerRadius,
width: 2*innerRadius, height: 2*innerRadius))
if !self.madeMask {
self.madeMask = true // do only once
self.mask = Mask(frame:CGRect(origin:.zero, size:rect.size))
}
}
}
I tried this with a sample setting as follows:
let v = Badge(frame: CGRect(x:100, y:100, width:16, height:16),
innerColor: .green, outerColor: .white, innerRadius: 5)
self.view.addSubview(v)
It looks fine. Adjust the parameters as desired.
I solved this by using a UIBezierPath and adding to the view's layer:
let strokePath = UIBezierPath(roundedRect: view.bounds, cornerRadius: view.frame.width / 2)
let stroke = CAShapeLayer()
stroke.frame = bounds
stroke.path = strokePath.cgPath
stroke.fillColor = .green.cgColor
stroke.lineWidth = 1.0
stroke.strokeColor = .white.cgColor
view.layer.insertSublayer(stroke, at: 2)
I solved this problem with gradients.
Just seting the backgroundColor of your circle as gradient.
let gradientLayer = CAGradientLayer()
//define colors
gradientLayer.colors = [<<your_bgc_color>>>>, <<border__bgc__color>>]
//define locations of colors as NSNumbers in range from 0.0 to 1.0
gradientLayer.locations = [0.0, 0.7]
//define frame
gradientLayer.frame = self.classView.bounds
self.classView.layer.insertSublayer(gradientLayer, at: 0)
MyImage
An easier fix might be to just mask it like this:
let mask = UIView()
mask.backgroundColor = .black
mask.frame = yourCircleView.bounds.inset(by: UIEdgeInsets(top: 0.1, left: 0.1, bottom: 0.1, right: 0.1))
mask.layer.cornerRadius = mask.height * 0.5
yourCircleView.mask = mask

Add text label to drawn shape

I'm following along with this tutorial for drawing squares where-ever there is a gesture recognized touch on the screen in iOS.
https://www.weheartswift.com/bezier-paths-gesture-recognizers/
I am now wanting to extend the functionality and want to add text labels to my newly drawn shapes indicating their coordinates.
So touching the screen would draw a rectangle, which moves with the pan gesture (so far so good) but I would also like it to show numbers indicating the coordinates.
How can I go about accomplishing this?
class CircularKeyView: UIView {
// a lot of this code came from https://www.weheartswift.com/bezier-paths-gesture-recognizers/
//all thanks goes to we<3swift
let lineWidth: CGFloat = 1.0
let size: CGFloat = 44.0
init(origin: CGPoint) {
super.init(frame: CGRectMake(0.0, 0.0, size, size))
self.center = origin
self.backgroundColor = UIColor.clearColor()
initGestureRecognizers() //start up all the gesture recognizers
}
func initGestureRecognizers() {
let panGR = UIPanGestureRecognizer(target: self, action: "didPan:")
addGestureRecognizer(panGR)
}
//PAN IT LIKE u FRYIN.
func didPan(panGR: UIPanGestureRecognizer) {
self.superview!.bringSubviewToFront(self)
var translation = panGR.translationInView(self)
self.center.x += translation.x
self.center.y += translation.y
panGR.setTranslation(CGPointZero, inView: self)
}
// We need to implement init(coder) to avoid compilation errors
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: 7)
//draws awesome curvy rectangle
UIColor.darkGrayColor().setFill()
path.fill()
//draws outline
path.lineWidth = self.lineWidth
UIColor.blackColor().setStroke()
path.stroke()
//////
//probably where I should draw the text label on this thing,
//although it needs to update when the thingy moves.
}
}
In your drawRect implementation you can draw the coordinates of the view with something like:
("\(frame.origin.x), \(frame.origin.y)" as NSString).drawAtPoint(.zero, withAttributes: [
NSFontAttributeName: UIFont.systemFontOfSize(14),
NSForegroundColorAttributeName: UIColor.blackColor()
])
Which simply creates a string of the coordinates, casts it to an NSString and then calls the drawAtPoint method to draw it in the view's context.
You can of course change .zero to any CGPoint depending on where you want to draw the string and can edit the attributes as desired.
To make sure that this gets updated when the user pans around you will want to also add:
self.setNeedsDisplay()
to the bottom of your didPan method.
Hope this helps :)

Resources