Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- import AppKit
- class IntensityView: NSView {
- override func draw(_ rect: CGRect) {
- drawMultipleShapesWithAColorGradient()
- }
- func drawMultipleShapesWithAColorGradient() {
- let height: Double = 500
- let startingMargin = 3.5
- guard let ctx = NSGraphicsContext.current else { return }
- let cgx = ctx.cgContext
- ctx.saveGraphicsState() /// Save out the state so that we dont clip everything outside of the path ctx.beginPath()
- cgx.move(to: CGPoint(x: 0, y: startingMargin))
- cgx.addLine(to: CGPoint(x: 25, y: startingMargin))
- cgx.addLine(to: CGPoint(x: 25, y: startingMargin + height))
- cgx.addLine(to: CGPoint(x: 0, y: startingMargin + height))
- cgx.closePath()
- cgx.clip() /// This is the clip we are referring to above.
- let locations: [CGFloat] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
- let colors: [CGFloat] = [
- 0.0, 0.0, 205/255, 1.0,
- 0.0, 75/255, 248/255, 1.0,
- 2/255, 209/255, 137/255, 1.0,
- 71/255, 250/255, 55/255, 1.0,
- 188/255, 255/255, 18/255, 1.0,
- 253/255, 252/255, 16/255, 1.0,
- 255/255, 219/255, 16/255, 1.0,
- 255/255, 137/255, 0/255, 1.0,
- 254/255, 61/255, 0/255, 1.0,
- 241/255, 0/255, 0/255, 1.0,
- 178/255, 11/255, 11/255, 1.0
- ]
- let colorSpace = CGColorSpaceCreateDeviceRGB()
- guard let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 11) else {
- return
- }
- cgx.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0.0), end: CGPoint(x: 0, y: height + startingMargin), options: CGGradientDrawingOptions(rawValue: 0))
- ctx.restoreGraphicsState() /// Restore the previous state. This will remove any paths, clipping, gradients, etc.
- let paragraphStyle = NSMutableParagraphStyle()
- paragraphStyle.alignment = .center
- let attributes = [
- NSAttributedString.Key.paragraphStyle: paragraphStyle,
- NSAttributedString.Key.font: NSFont.systemFont(ofSize: 12.0),
- NSAttributedString.Key.foregroundColor: NSColor.white
- ]
- (0...10).forEach { index in
- cgx.move(to: CGPoint(x: 0, y: startingMargin + Double(index) * (height) / 10))
- cgx.addLine(to: CGPoint(x: 38, y: startingMargin + Double(index) * (height) / 10))
- cgx.setLineWidth(1)
- cgx.setStrokeColor(#colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1))
- cgx.strokePath()
- let labelText = "\(index - 3)"
- let attributedString = NSAttributedString(string: labelText, attributes: attributes)
- let stringRect = CGRect(x: 38, y: 0.0 + Double(index) * height / 10, width: 20, height: 12)
- attributedString.draw(in: stringRect)
- }
- ctx.cgContext.setFillColor(.clear)
- ctx.cgContext.setStrokeColor(.white)
- ctx.cgContext.setLineWidth(1)
- let rectangle = CGRect(x: 0, y: startingMargin, width: 26, height: height)
- ctx.cgContext.addRect(rectangle)
- ctx.cgContext.drawPath(using: .fillStroke)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement