Drawing a dotted background in swift - swift

Im trying to achieve a dotted view that I can use as a background. Something looking a bit like this:
But I seem to be missing something in my code. I have tried to lab around with different sizes of the dots and everything, but so far I'm just getting my background color set to the view but no dots no matter the size, the color or the spacing. What am I missing?
class DottedBackgroundView: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
UIColor.green.setFill()
context.fill(rect)
let drawPattern: CGPatternDrawPatternCallback = { _, context in
context.addArc(
center: CGPoint(x: 5, y: 5), radius: 2.5,
startAngle: 0, endAngle: CGFloat(2.0 * .pi),
clockwise: false)
context.setFillColor(UIColor.white.cgColor)
context.fillPath()
}
var callbacks = CGPatternCallbacks(
version: 0, drawPattern: drawPattern, releaseInfo: nil)
let pattern = CGPattern(
info: nil,
bounds: CGRect(x: 0, y: 0, width: 10, height: 10),
matrix: .identity,
xStep: 10,
yStep: 10,
tiling: .constantSpacing,
isColored: true,
callbacks: &callbacks)
let patternSpace = CGColorSpace(patternBaseSpace: nil)!
context.setFillColorSpace(patternSpace)
var alpha: CGFloat = 1.0
context.setFillPattern(pattern!, colorComponents: &alpha)
context.fill(rect)
context.addArc(
center: CGPoint(x: 5, y: 5), radius: 5.0,
startAngle: 0, endAngle: CGFloat(2.0 * .pi),
clockwise: false)
}
}

You have a bug. Just change second line to UIColor.white.setFill() and inside drawPattern change color to black: context.setFillColor(UIColor.black.cgColor).
It works. I set this view on Storyboard, but if you add it from code try this:
let dottedView = DottedBackgroundView()
dottedView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(dottedView)
NSLayoutConstraint.activate([
dottedView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
dottedView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
dottedView.topAnchor.constraint(equalTo: self.view.topAnchor),
dottedView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
You need to set constraints, because your custom view doesn't have defined size, therefore it's not able to resize properly.

Related

curve in tabbar view and bottom popup not working?

Hello all, I tried to add arc for UIBezierPath I could not able to get the exact curve,
here is my code here I have added the bezier path for the added curve from the center position.
#IBDesignable
class MyTabBar: UITabBar {
private var shapeLayer: CALayer?
private func addShape() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = createPath()
shapeLayer.strokeColor = UIColor.lightGray.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.lineWidth = 1.0
//The below 4 lines are for shadow above the bar. you can skip them if you do not want a shadow
shapeLayer.shadowOffset = CGSize(width:0, height:0)
shapeLayer.shadowRadius = 10
shapeLayer.shadowColor = UIColor.gray.cgColor
shapeLayer.shadowOpacity = 0.3
if let oldShapeLayer = self.shapeLayer {
self.layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
} else {
self.layer.insertSublayer(shapeLayer, at: 0)
}
self.shapeLayer = shapeLayer
}
override func draw(_ rect: CGRect) {
self.addShape()
}
func createPath() -> CGPath {
let height: CGFloat = 37.0
let path = UIBezierPath()
let centerWidth = self.frame.width / 2
path.move(to: CGPoint(x: 0, y: 0)) // start top left
path.addLine(to: CGPoint(x: (centerWidth - height * 2), y: 0)) // the beginning of the trough
path.addCurve(to: CGPoint(x: centerWidth, y: height),
controlPoint1: CGPoint(x: (centerWidth - 30), y: 0), controlPoint2: CGPoint(x: centerWidth - 35, y: height))
path.addCurve(to: CGPoint(x: (centerWidth + height * 2), y: 0),
controlPoint1: CGPoint(x: centerWidth + 35, y: height), controlPoint2: CGPoint(x: (centerWidth + 30), y: 0))
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
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard !clipsToBounds && !isHidden && alpha > 0 else { return nil }
for member in subviews.reversed() {
let subPoint = member.convert(point, from: self)
guard let result = member.hitTest(subPoint, with: event) else { continue }
return result
}
return nil
}
}
this is tab bar controller added plus button in center view center, and the when tap the plus button to add the curve based popup should show, I don't know how to add curve based popup.
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.navigationController?.navigationBar.isHidden = true
setupMiddleButton()
}
// TabBarButton – Setup Middle Button
func setupMiddleButton() {
let middleBtn = UIButton(frame: CGRect(x: (self.view.bounds.width / 2)-25, y: -20, width: 50, height: 50))
middleBtn.setImage(UIImage(named: "PlusBtn"), for: .normal)
self.tabBar.addSubview(middleBtn)
middleBtn.addTarget(self, action: #selector(self.menuButtonAction), for: .touchUpInside)
self.view.layoutIfNeeded()
}
// Menu Button Touch Action
#objc func menuButtonAction(sender: UIButton) {
//show the popUp
}
}
Please share me the findings & share me your refreance
Thanks
New edit:
I created a general-purpose method that will generate polygons with a mixture of sharp and rounded corners of different radii. I used it to create a project with a look rather like what you are after. You can download it from Github:
https://github.com/DuncanMC/CustomTabBarController.git
Here's what it looks like:
Note that the area of the tab's view controller that extends into the tab bar controller does not get taps. If you try to tap there, it triggers the tab bar controller. You will have to do some more tinkering to get that part to work.
Ultimately you may have to create a custom UITabBar (or UITabBar-like component) and possibly a custom parent view controller that acts like a UITabBar, in order to get what you want.
The method that creates polygon paths is called buildPolygonPathFrom(points:defaultCornerRadius:)
It takes an array of PolygonPoint structs. Those are defined like this:
/// A struct describing a single vertex in a polygon. Used in building polygon paths with a mixture of rounded an sharp-edged vertexes.
public struct PolygonPoint {
let point: CGPoint
let isRounded: Bool
let customCornerRadius: CGFloat?
init(point: CGPoint, isRounded: Bool, customCornerRadius: CGFloat? = nil) {
self.point = point
self.isRounded = isRounded
self.customCornerRadius = customCornerRadius
}
init(previousPoint: PolygonPoint, isRounded: Bool) {
self.init(point: previousPoint.point, isRounded: isRounded, customCornerRadius: previousPoint.customCornerRadius)
}
}
The code to build the path for the custom tab bar looks like this:
func tabBarMaskPath() -> CGPath? {
let width = bounds.width
let height = bounds.height
guard width > 0 && height > 0 else { return nil }
let dentRadius: CGFloat = 35
let cornerRadius: CGFloat = 20
let topFlatPartWidth = (width - dentRadius * 2.0) / 2
let polygonPoints = [
PolygonPoint(point: CGPoint(x: 0, y: 0), // Point 0
isRounded: true,
customCornerRadius: cornerRadius),
PolygonPoint(point: CGPoint(x: 0, y: height), // Point 1
isRounded: false),
PolygonPoint(point: CGPoint(x: width, y: height), // Point 2
isRounded: false),
PolygonPoint(point: CGPoint(x: width, y: 0), // Point 3
isRounded: true,
customCornerRadius: cornerRadius),
PolygonPoint(point: CGPoint(x: topFlatPartWidth + dentRadius * 2, y: 0), // Point 4
isRounded: true,
customCornerRadius: cornerRadius),
PolygonPoint(point: CGPoint(x: topFlatPartWidth + dentRadius * 2, y: dentRadius + cornerRadius), // Point 5
isRounded: true,
customCornerRadius: dentRadius),
PolygonPoint(point: CGPoint(x: topFlatPartWidth , y: dentRadius + cornerRadius), // Point 6
isRounded: true,
customCornerRadius: dentRadius),
PolygonPoint(point: CGPoint(x: topFlatPartWidth , y: 0), // Point 7
isRounded: true,
customCornerRadius: cornerRadius),
]
return buildPolygonPathFrom(points: polygonPoints, defaultCornerRadius: 0)
}
Previous answer:
I just tried it, and it is possible to subclass UITabBar. I created a subclass of UITabBar where I use a mask layer to cut a circular "notch" out of the top of the tab bar. The code is below. It looks like the screenshot below. It isn't quite what you're after, but it's a start:
(The background color for the "Page 1" view controller is set to light gray, and you can see that color showing through in the "notch" I cut out of the tab bar.)
//
// CustomTabBar.swift
// TabBarController
//
// Created by Duncan Champney on 3/31/21.
//
import UIKit
class CustomTabBar: UITabBar {
var maskLayer = CAShapeLayer()
override var frame: CGRect {
didSet {
configureMaskLayer()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configureMaskLayer()
self.layer.mask = maskLayer
self.layer.borderWidth = 0
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureMaskLayer()
self.layer.mask = maskLayer
}
func configureMaskLayer() {
let rect = layer.bounds
maskLayer.frame = rect
let circleBoxSize = rect.size.height * 1.25
maskLayer.fillRule = .evenOdd
let path = UIBezierPath(rect: rect)
let circleRect = CGRect(x: rect.size.width/2 - circleBoxSize / 2,
y: -circleBoxSize/2,
width: circleBoxSize,
height: circleBoxSize)
let circle = UIBezierPath.init(ovalIn: circleRect)
path.append(circle)
maskLayer.path = path.cgPath
maskLayer.fillColor = UIColor.white.cgColor // Any opaque color works and has no effect
}
}
Edit:
To draw your popover view you'll need to create a filled path that shape. You'll have to construct a custom shape like that with a combination of lines and arcs. I suggest using a CGMutablePath and the method addArc(tangent1End:tangent2End:radius:transform:) since that enables you to provide endpoints rather than angles.
Edit #2:
Another part of the puzzle:
Here is a custom UIView subclass that masks itself in the shape you're after
//
// ShapeWithTabView.swift
// ShapeWithTab
//
// Created by Duncan Champney on 4/1/21.
//
import UIKit
class ShapeWithTabView: UIView {
var cornerRadius: CGFloat = 20
var tabRadius: CGFloat = 60
var tabExtent: CGFloat = 0
var shapeLayer = CAShapeLayer()
var maskLayer = CAShapeLayer()
func buildShapeLayerPath() -> CGPath {
let boxWidth = min(bounds.size.width - 40, 686)
let boxHeight = min(bounds.size.height - 40 - tabRadius * 2 - tabExtent, 832)
// These are the corners of the view's primary rectangle
let point1 = CGPoint(x: 0, y: boxHeight)
let point2 = CGPoint(x: 0, y: 0)
let point3 = CGPoint(x: boxWidth, y: 0)
let point4 = CGPoint(x: boxWidth, y: boxHeight)
// These are the corners of the "tab" that extends outside the view's normal bounds.
let tabPoint1 = CGPoint(x: boxWidth / 2 + tabRadius, y: boxHeight)
let tabPoint2 = CGPoint(x: boxWidth / 2 + tabRadius, y: boxHeight + tabExtent + tabRadius * 2 )
let tabPoint3 = CGPoint(x: boxWidth / 2 - tabRadius, y: boxHeight + tabExtent + tabRadius * 2)
let tabPoint4 = CGPoint(x: boxWidth / 2 - tabRadius , y: boxHeight)
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: boxHeight - cornerRadius))
path.addArc(tangent1End: point2,
tangent2End: point3,
radius: cornerRadius)
path.addArc(tangent1End: point3,
tangent2End: point4,
radius: cornerRadius)
path.addArc(tangent1End: point4,
tangent2End: point1,
radius: cornerRadius)
//
path.addArc(tangent1End: tabPoint1,
tangent2End: tabPoint2,
radius: tabRadius)
path.addArc(tangent1End: tabPoint2,
tangent2End: tabPoint3,
radius: tabRadius)
path.addArc(tangent1End: tabPoint3,
tangent2End: tabPoint4,
radius: tabRadius)
path.addArc(tangent1End: tabPoint4,
tangent2End: point1,
radius: tabRadius)
path.addArc(tangent1End: point1,
tangent2End: point2,
radius: cornerRadius)
return path
}
func doInitSetup() {
self.layer.addSublayer(shapeLayer)
self.layer.mask = maskLayer
backgroundColor = .lightGray
//Configure a shape layer to draw an outline
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 2
//Configure a mask layer to mask the view to our custom shape
maskLayer.fillColor = UIColor.white.cgColor
maskLayer.strokeColor = UIColor.white.cgColor
maskLayer.lineWidth = 2
}
override init(frame: CGRect) {
super.init(frame: frame)
self.doInitSetup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.doInitSetup()
}
public func updateShapeLayerPath() {
let path = buildShapeLayerPath()
shapeLayer.path = path
maskLayer.path = path
}
override var frame: CGRect {
didSet {
print("New frame = \(frame)")
shapeLayer.frame = layer.bounds
}
}
}
Combined with the modified tab bar from above, it looks like the image below. The final task is to get the custom view sized and positioned correctly, and have it land on top of the tab bar.

How do you trace the border of an iPhone screen (including the notch for an X, 11, or 12 series)?

I'm trying to trace a line around the outside of the main view - trace along the edge of the screen. The following image shows the outline, and the code below shows how it animates.
The problem is, the animation draws the outer edge first, and then it draws the area around the notch.
I need it to start to draw the outer edge, drop down and draw around the notch, and then continue along the outer edge until it finishes.
import UIKit
class ViewController: UIViewController {
var layer: CAShapeLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
setupBorder()
animateBorder()
}
func setupBorder() {
let bounds = self.view.bounds
if UIDevice.current.hasNotch {
// FIXME: needs tweaks for:
// 12 pro max (corners and notch)
// 12 pro (corners)
// 12 mini (notch)
// the math works for all X and 11 series
// border around the phone screen
let framePath = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 40, height: 40))
// Math courtesy of:
// https://www.paintcodeapp.com/news/iphone-x-screen-demystified
let devicePointWidth = UIScreen.main.bounds.size.width
let w = devicePointWidth * 83 / 375
let n = devicePointWidth * 209 / 375
let notchBounds = CGRect(x: w, y: -10, width: n, height: 40)
let notchPath = UIBezierPath(roundedRect: notchBounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 20, height: 20))
// This is the problem. The framePath is drawn first,
// and then the notchPath is drawn. I need these to be
// mathematically merged
framePath.append(notchPath)
framePath.usesEvenOddFillRule = true
layer.path = framePath.cgPath
} else {
// if device is an 8 or lower, the border of the screen
// is a rectangle
layer.path = UIBezierPath(rect: bounds).cgPath
}
layer.strokeColor = UIColor.blue.cgColor
layer.strokeEnd = 0.0
layer.lineWidth = 20.0
layer.fillColor = nil
self.view.layer.addSublayer(layer)
}
func animateBorder() {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.strokeEnd))
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 6
CATransaction.setCompletionBlock { [weak self] in
self?.layer.strokeColor = UIColor.cyan.cgColor
self?.layer.strokeEnd = 1.0
}
layer.add(animation, forKey: "stroke-screen")
CATransaction.commit()
}
}
extension UIDevice {
var hasNotch: Bool {
// FIXME: Does not work with apps that use SceneDelegate
// Requires the window var in the AppDelegate
if #available(iOS 11.0, *) {
return UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0 > 20
}
return false
}
}
The code above can be used in a new project, BUT the SceneDelegate.swift file will need to be removed, the Application Scene Manifest entry in the Info.plist will need to be deleted, and var window: UIWindow? will need to be added to AppDelegate.swift.
You're having that issue because you're creating two separate shapes and appending one to the next. So your path is being properly drawn.
You need to create one shape by using the exact coordinates so its properly drawn.
Here's a simple shape without any rounded corners:
let framePath = UIBezierPath()
framePath.move(to: .zero)
framePath.addLine(to: CGPoint(x: w, y: 0))
framePath.addLine(to: CGPoint(x: w, y: 30))
framePath.addLine(to: CGPoint(x: w+n, y: 30))
framePath.addLine(to: CGPoint(x: w+n, y: 0))
framePath.addLine(to: CGPoint(x: devicePointWidth, y: 0))
framePath.addLine(to: CGPoint(x: devicePointWidth, y: self.view.bounds.height))
framePath.addLine(to: CGPoint(x: 0, y: self.view.bounds.height))
framePath.addLine(to: .zero)
Then you can user addArc(withCenter:radius:startAngle:endAngle:clockwise:) to add the curved parts.
Here is a rough draft using some of the values that you had calculated:
let circleTop = CGFloat(3*Double.pi / 2)
let circleRight = CGFloat(0)
let circleBottom = CGFloat(Double.pi / 2)
let circleLeft = CGFloat(Double.pi)
let framePath = UIBezierPath()
framePath.move(to: CGPoint(x: 40, y: 0))
framePath.addLine(to: CGPoint(x: w-6, y: 0))
framePath.addArc(withCenter: CGPoint(x: w-6, y: 6), radius: 6, startAngle: circleTop, endAngle: circleRight, clockwise: true)
framePath.addArc(withCenter: CGPoint(x: w+20, y: 10), radius: 20, startAngle: circleLeft, endAngle: circleBottom, clockwise: false)
framePath.addLine(to: CGPoint(x: w+n-20, y: 30))
framePath.addArc(withCenter: CGPoint(x: w+n-20, y: 10), radius: 20, startAngle: circleBottom, endAngle: circleRight, clockwise: false)
framePath.addArc(withCenter: CGPoint(x: w+n+6, y: 6), radius: 6, startAngle: CGFloat(Double.pi), endAngle: circleTop, clockwise: true)
framePath.addLine(to: CGPoint(x: devicePointWidth-40, y: 0))
framePath.addArc(withCenter: CGPoint(x: devicePointWidth-40, y: 40), radius: 40, startAngle: circleTop, endAngle: circleRight, clockwise: true)
framePath.addLine(to: CGPoint(x: devicePointWidth, y: self.view.bounds.height - 40))
framePath.addArc(withCenter: CGPoint(x: UIScreen.main.bounds.size.width-40, y: UIScreen.main.bounds.size.height-40), radius: 40, startAngle: circleRight, endAngle: circleBottom, clockwise: true)
framePath.addLine(to: CGPoint(x: 40, y: self.view.bounds.height))
framePath.addArc(withCenter: CGPoint(x: 40, y: UIScreen.main.bounds.size.height-40), radius: 40, startAngle: circleBottom, endAngle: circleLeft, clockwise: true)
framePath.addLine(to: CGPoint(x: 0, y: 40))
framePath.addArc(withCenter: CGPoint(x: 40, y: 40), radius: 40, startAngle: circleLeft, endAngle: circleTop, clockwise: true)

How to draw text when using layers in NSView with Swift

I'm using layers in my NSView as much of the display will change infrequently. This is working fine. I'm now at the point where I'd like to add text to the layer. This is not working.
To draw the text, I'm trying to use code from another answer on how to draw text on a curve. I've researched and nothing I've tried helps. I've created a Playground to demonstrate. I can see when I run the Playground that the code to display the text is actually called, but nothing is rendered to the screen. I'm sure I've got something wrong, just not sure what.
The playground is below, along with the code referenced from above (updated for Swift 5, NS* versus UI*, and comments removed for size).
import AppKit
import PlaygroundSupport
func centreArcPerpendicular(text str: String,
context: CGContext,
radius r: CGFloat,
angle theta: CGFloat,
colour c: NSColor,
font: NSFont,
clockwise: Bool){
let characters: [String] = str.map { String($0) }
let l = characters.count
let attributes = [NSAttributedString.Key.font: font]
var arcs: [CGFloat] = []
var totalArc: CGFloat = 0
for i in 0 ..< l {
arcs += [chordToArc(characters[i].size(withAttributes: attributes).width, radius: r)]
totalArc += arcs[i]
}
let direction: CGFloat = clockwise ? -1 : 1
let slantCorrection: CGFloat = clockwise ? -.pi / 2 : .pi / 2
var thetaI = theta - direction * totalArc / 2
for i in 0 ..< l {
thetaI += direction * arcs[i] / 2
centre(text: characters[i],
context: context,
radius: r,
angle: thetaI,
colour: c,
font: font,
slantAngle: thetaI + slantCorrection)
thetaI += direction * arcs[i] / 2
}
}
func chordToArc(_ chord: CGFloat, radius: CGFloat) -> CGFloat {
return 2 * asin(chord / (2 * radius))
}
func centre(text str: String,
context: CGContext,
radius r: CGFloat,
angle theta: CGFloat,
colour c: NSColor,
font: NSFont,
slantAngle: CGFloat) {
let attributes = [NSAttributedString.Key.foregroundColor: c, NSAttributedString.Key.font: font]
context.saveGState()
context.translateBy(x: r * cos(theta), y: -(r * sin(theta)))
context.rotate(by: -slantAngle)
let offset = str.size(withAttributes: attributes)
context.translateBy (x: -offset.width / 2, y: -offset.height / 2)
str.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
context.restoreGState()
}
class CustomView: NSView {
let textOnCurve = TextOnCurve()
override init(frame: NSRect) {
super.init(frame: frame)
wantsLayer = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLayer() {
let textOnCurveLayer = CAShapeLayer()
textOnCurveLayer.frame = self.frame
textOnCurveLayer.delegate = textOnCurve
textOnCurveLayer.setNeedsDisplay()
layer?.addSublayer(textOnCurveLayer)
}
}
class TextOnCurve: NSObject, CALayerDelegate {
func draw(_ layer: CALayer, in ctx: CGContext) {
ctx.setFillColor(.white)
ctx.move(to: CGPoint(x: 100, y: 100))
ctx.addLine(to: CGPoint(x: 150, y: 100))
ctx.addLine(to: CGPoint(x: 150, y: 150))
ctx.addLine(to: CGPoint(x: 100, y: 150))
ctx.closePath()
ctx.drawPath(using: .fill)
ctx.translateBy(x: 200.0, y: 200.0)
centreArcPerpendicular(text: "Anticlockwise",
context: ctx,
radius: 100,
angle: CGFloat(-.pi/2.0),
colour: .red,
font: NSFont.systemFont(ofSize: 16),
clockwise: false)
centre(text: "Hello flat world",
context: ctx,
radius: 0,
angle: 0 ,
colour: .yellow,
font: NSFont.systemFont(ofSize: 16),
slantAngle: .pi / 4)
}
}
let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
PlaygroundPage.current.liveView = containerView
The box is drawn, but the text is not.
If I do not use layers, then I can draw text by calling the methods in the standard draw: method. So the code should work, but, something about the use of layers is preventing it.

Drawing a simple line chart using Swift

I am writing a Swift program using Xcode 9.2 for the MacOS with the objecting of displaying a simple line chart with three points.
The program's objective is to create a line graph using apple's core graphics. It is a horizontal line graph with three points, one at the center and at each end. If the mouse pointer is over the center point I want some text to display like "xyz" and when the mouse moves away the text would disappear. The end points will have labels containing numbers but for now let's call them "min" and "max".
Using XCode's playground, so far I have managed to accomplish to display a very clunky line graph using the following code:
class MyView : NSView {
override func draw(_ rect: NSRect) {
NSColor.green.setFill()
var path = NSBezierPath(rect: self.bounds)
path.fill()
let leftDot = NSRect(x: 0, y: 0, width: 10, height: 20)
path = NSBezierPath(ovalIn: leftDot)
NSColor.black.setFill()
path.fill()
let rightDot = NSRect(x: 90, y: 0, width: 10, height: 20)
path = NSBezierPath(ovalIn: rightDot)
NSColor.black.setFill()
path.fill()
let centerDot = NSRect(x: 50, y: 0, width: 10, height: 20)
path = NSBezierPath(ovalIn: centerDot)
NSColor.black.setFill()
path.fill()
}
}
let viewRect = NSRect(x: 0, y: 0, width: 100, height: 10)
let myEmptyView = MyView(frame: viewRect)
The code produces a clunky looking line graph as follows:
The chart below is from Excel and this line chart is much cleaner and is what I am looking for but I want the line to be horizontal instead of diagonal.
Thanks in advance for your help.
To draw a horizontal line similar to the sample image you provided, I took your sample code and modified it. This would give this result:
The code would look like this then:
override func draw(_ rect: NSRect) {
NSColor(red: 103/255, green: 146/255, blue: 195/255, alpha: 1).set()
let line = NSBezierPath()
line.move(to: NSMakePoint(10, 5))
line.line(to: NSMakePoint(90, 5))
line.lineWidth = 2
line.stroke()
NSColor(red: 163/255, green: 189/255, blue: 218/255, alpha: 1).setFill()
let origins = [NSPoint(x: 10, y: 1),
NSPoint(x: 50, y: 1),
NSPoint(x: 90, y: 1)]
let size = NSSize(width: 8, height: 8)
for origin in origins {
let quad = NSBezierPath(roundedRect: NSRect(origin: origin, size: size), xRadius: 2, yRadius: 2)
quad.fill()
quad.stroke()
}
}
Update for iOS
Due to a request in the comments section here the iOS variant:
override func draw(_ rect: CGRect) {
UIColor(red: 103/255, green: 146/255, blue: 195/255, alpha: 1).set()
let line = UIBezierPath()
line.move(to: CGPoint(x: 10, y:5))
line.addLine(to: CGPoint(x: 90, y:5))
line.lineWidth = 2
line.stroke()
UIColor(red: 163/255, green: 189/255, blue: 218/255, alpha: 1).setFill()
let origins = [CGPoint(x: 10, y: 1),
CGPoint(x: 50, y: 1),
CGPoint(x: 90, y: 1)]
let size = CGSize(width: 8, height: 8)
for origin in origins {
let quad = UIBezierPath.init(roundedRect: CGRect(origin: origin, size: size), cornerRadius: 2)
quad.fill()
quad.stroke()
}
}
Alternatively, you could add a CAShapeLayer sublayer whose path property is a UIBezierPath to the UIView.

How to cut edges of a uiview in swift

I attached the View image. I want to achieve the small cut in bottom between the buy button and above flight information view.
I think the easiest way would be to create 2 circles as plain UIView instances and set their center as the left and right edges of the parent view respectively.
Since you set clipsToBounds to true, they will be clipped and only half of them will be visible on the screen.
public class TestView: UIView {
private let leftCircle = UIView(frame: .zero)
private let rightCircle = UIView(frame: .zero)
public var circleY: CGFloat = 0
public var circleRadius: CGFloat = 0
public override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
addSubview(leftCircle)
addSubview(rightCircle)
}
public override func layoutSubviews() {
super.layoutSubviews()
leftCircle.frame = CGRect(x: -circleRadius, y: circleY,
width: circleRadius * 2 , height: circleRadius * 2)
leftCircle.layer.masksToBounds = true
leftCircle.layer.cornerRadius = circleRadius
rightCircle.frame = CGRect(x: bounds.width - circleRadius, y: circleY,
width: circleRadius * 2 , height: circleRadius * 2)
rightCircle.layer.masksToBounds = true
rightCircle.layer.cornerRadius = circleRadius
}
}
I've created a sample project demonstrating that. Here is how it looks in my simulator (iPhone SE 11.2):
I had to do this with shadows. I tried creating a layer and subtracting another layer from it using evenOdd fillRule, however that didn't work since I need a specific path for shadows and evenOdd applies to the filling in the path instead.
In the end I just created the path manually
func setShadowPath() {
let path = UIBezierPath()
path.move(to: bounds.origin)
path.addLine(to: CGPoint(x: cutoutView.frame.minX, y: bounds.minY))
path.addArc(withCenter: CGPoint(x: cutoutView.frame.midX, y: bounds.minY),
radius: cutoutView.bounds.width/2, startAngle: .pi, endAngle: 0, clockwise: false)
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.close()
layer.shadowPath = path.cgPath
}
I created a "cutoutView" in my xib so I could trace around it easily.
That makes the shadow the correct shape, and then in order to create the cut itself I just created a layer using that same path
func setupBackground() {
let backgroundLayer = CAShapeLayer()
backgroundLayer.path = layer.shadowPath
backgroundLayer.fillColor = UIColor.white.cgColor
layer.insertSublayer(backgroundLayer, at: 0)
}