Matching node.fillColor (SKShapeNode) - swift

I have 25 circles on screen each with a random colour that has been generated from the declared colours and each names 'CIRCLE_1', 'CIRCLE_2' etc.
When matching the node.fillColor with the pre-defined colours, only the Yellow returns a value. Everything else remains at 0.
Can't see what I'm doing wrong/missing.
let SDRed = SKColor(red: 255/255, green: 61/255, blue: 61/255, alpha: 1.0)
let SDBlue = SKColor(red: 0/255, green: 175/255, blue: 255/255, alpha: 1.0)
let SDYellow = SKColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1.0)
let SDOrange = SKColor(red: 255/255, green: 128/255, blue: 0/255, alpha: 1.0)
let SDPink = SKColor(red: 255/255, green: 105/255, blue: 180/255, alpha: 1.0)
let SDGreen = SKColor(red: 144/255, green: 238/255, blue: 144/255, alpha: 1.0)
let SDDodgerBlue = SKColor(red: 30/255, green: 144/255, blue: 255/255, alpha: 1.0)
func checkAllColoursAvailable() -> Bool {
var yellow = 0
var blue = 0
var pink = 0
var green = 0
var red = 0
var orange = 0
enumerateChildNodes(withName: "CIRCLE_*", using:
{ (node, stop) -> Void in
print((node as! SKShapeNode).name!)
let col: SKColor = (node as! SKShapeNode).fillColor
if col == SDYellow {
yellow = yellow + 1
} else if col == SDGreen {
green = green + 1
} else if col == SDDodgerBlue {
blue = blue + 1
} else if col == SDOrange {
orange = orange + 1
} else if col == SDRed {
red = red + 1
} else if col == SDPink {
pink = pink + 1
}
})
if yellow >= 1 && blue >= 1 && green >= 1 && orange >= 1 && red >= 1 && pink >= 1 {
return true
} else {
return false
}
}

Related

spaceMin and spaceMax in swift Charts not working

I am using charts for linechart and I am trying to add space on the left and right sides of the line.
let xAxis = chtChart.xAxis
xAxis.spaceMax = 0.5
xAxis.spaceMin = 0.5
but space does not add and also chart does not plot at all.
Full xAxis setup is here:
let xAxis = chtChart.xAxis
xAxis.spaceMax = 0.5
xAxis.spaceMin = 0.5
xAxis.labelPosition = .bottom
xAxis.gridLineDashPhase = 0
xAxis.axisLineWidth = CGFloat(2)
xAxis.avoidFirstLastClippingEnabled = true
xAxis.gridColor = UIColor(red: 0.76, green: 0.76, blue: 0.76, alpha: 1.0)
xAxis.gridLineDashLengths = [5, 5]
xAxis.axisLineColor = #colorLiteral(red: 1, green: 0, blue: 0.2392156863, alpha: 1)
xAxis.axisMinimum = 0
xAxis.granularity = 1
xAxis.labelCount = 12
xAxis.valueFormatter = self
xAxis.labelFont = .OpenInter(.regular, size: 10)
xAxis.labelTextColor = UIColor(red: 0.49, green: 0.49, blue: 0.49, alpha: 1.00)
chtChart.animate(xAxisDuration: 3.0, yAxisDuration: 3.0)
what am I missing here?
graph shown in image is plot after removing xAxis.spaceMax = 0.5 ,xAxis.spaceMin = 0.5

How to get a string from a CGColor MacOS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to make an app to make it easier to select certain colors and for me to use the NSPasteboard.setString command I need to format the color as a string. Is there a way I can change a CGColor into a string?
Thanks!
Here's a useful extension I made for doing this with CGColor. You can get the RGBA components, as well as convert them back.
Code:
extension CGColor {
/// Components of a color. Contains `rgba`.
struct Components: Codable {
let red: CGFloat
let green: CGFloat
let blue: CGFloat
let alpha: CGFloat
init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
init?(rgba: [CGFloat]) {
guard rgba.count == 4 else { return nil }
red = rgba[0]
green = rgba[1]
blue = rgba[2]
alpha = rgba[3]
}
var all: [CGFloat] {
[red, green, blue, alpha]
}
}
var components: Components? {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
_ = NSColor(cgColor: self)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let components = [red, green, blue, alpha]
return Components(rgba: components)
}
static func create(from components: Components) -> CGColor {
self.init(
red: components.red,
green: components.green,
blue: components.blue,
alpha: components.alpha
)
}
}
Usage:
if let components = CGColor(red: 1, green: 0.2, blue: 0.2, alpha: 1).components {
print(components)
let new = CGColor.create(from: components)
print(new)
}
Prints: Components(red: 1.0, green: 0.2, blue: 0.2, alpha: 1.0)
Prints: <CGColor 0x600003f1d500> [<CGColorSpace 0x600003f1ab80> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; Generic RGB Profile)] ( 1 0.2 0.2 1 )

MapKit - problem with showing the user location and the MKPolygon Area

I'm having a problem with trying to display the user location and the MKPolygon Area.
Here is the code about the MapView.swift:
import SwiftUI
import MapKit
let model = Model(filename: "ZONE_LIST")
var mapView = MKMapView() // (frame: UIScreen.main.bounds)
var theme = ""
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let latDelta = model.overlayTopLeftCoordinate.latitude - model.overlayBottomRightCoordinate.latitude
let span = MKCoordinateSpan(latitudeDelta: fabs(latDelta), longitudeDelta: 0.99)
let region = MKCoordinateRegion(center: model.midCoordinate, span: span)
mapView.showsUserLocation = true
mapView.region = region
mapView.delegate = context.coordinator
return mapView
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {}
}
The Coordinator file instead is:
import MapKit
final class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolygon {
let polygonView = MKPolygonRenderer(overlay: overlay)
if theme == "Ciano" {
polygonView.strokeColor = .cyan
polygonView.fillColor = .cyan
} else if theme == "Rosso" {
polygonView.strokeColor = .init(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0)
} else if theme == "Verde" {
polygonView.strokeColor = .init(red: 0/255, green: 255/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 255/255, blue: 0/255, alpha: 1.0)
} else if theme == "Magenta" {
polygonView.strokeColor = .magenta
polygonView.fillColor = .magenta
} else if theme == "Giallo" {
polygonView.strokeColor = .yellow
polygonView.fillColor = .yellow
} else if theme == "Arancione" {
polygonView.strokeColor = .init(red: 255/255, green: 153/255, blue: 51/255, alpha: 1.0)
polygonView.fillColor = .init(red: 255/255, green: 153/255, blue: 51/255, alpha: 1.0)
} else if theme == "Verde Turchese" {
polygonView.strokeColor = .init(red: 50/255, green: 198/255, blue: 166/255, alpha: 1.0)
polygonView.fillColor = .init(red: 50/255, green: 198/255, blue: 166/255, alpha: 1.0)
} else if theme == "Blu" {
polygonView.strokeColor = .init(red: 0/255, green: 66/255, blue: 255/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 66/255, blue: 255/255, alpha: 1.0)
} else {
polygonView.strokeColor = .init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}
polygonView.alpha = 0.5
polygonView.lineWidth = 5.0
return polygonView
}
return MKOverlayRenderer()
}
}
To be honest, this is the code in the exact moment I have got the error trying to put the UserLocation on the Project, however the problem is this. I hope someone can help me.
Ok boyz, the problem has been resolved by myself, lol.
I just putted in the Coordinator.swift file the code that print out the marked area.
final class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is ModelMapOverlay {
return ModelMapOverlayView(overlay: overlay, overlayImage: UIImage(imageLiteralResourceName: "overlay_model"))
} else if overlay is MKPolyline {
let lineView = MKPolylineRenderer(overlay: overlay)
lineView.strokeColor = .green
return lineView
} else if overlay is MKPolygon {
let polygonView = MKPolygonRenderer(overlay: overlay)
if theme == "Ciano" {
polygonView.strokeColor = .cyan
polygonView.fillColor = .cyan
} else if theme == "Rosso" {
polygonView.strokeColor = .init(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0)
} else if theme == "Verde" {
polygonView.strokeColor = .init(red: 0/255, green: 255/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 255/255, blue: 0/255, alpha: 1.0)
} else if theme == "Magenta" {
polygonView.strokeColor = .magenta
polygonView.fillColor = .magenta
} else if theme == "Giallo" {
polygonView.strokeColor = .yellow
polygonView.fillColor = .yellow
} else if theme == "Arancione" {
polygonView.strokeColor = .init(red: 255/255, green: 153/255, blue: 51/255, alpha: 1.0)
polygonView.fillColor = .init(red: 255/255, green: 153/255, blue: 51/255, alpha: 1.0)
} else if theme == "Verde Turchese" {
polygonView.strokeColor = .init(red: 50/255, green: 198/255, blue: 166/255, alpha: 1.0)
polygonView.fillColor = .init(red: 50/255, green: 198/255, blue: 166/255, alpha: 1.0)
} else if theme == "Blu" {
polygonView.strokeColor = .init(red: 0/255, green: 66/255, blue: 255/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 66/255, blue: 255/255, alpha: 1.0)
} else {
polygonView.strokeColor = .init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
polygonView.fillColor = .init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}
polygonView.alpha = 0.5
polygonView.lineWidth = 5.0
return polygonView
} else if let character = overlay as? Character {
let circleView = MKCircleRenderer(overlay: character)
circleView.strokeColor = character.color
return circleView
}
return MKOverlayRenderer()
}
}
Hope if someone will got the same problem could see this snippet to resolve it

How to programmatically change the background color of the view [duplicate]

I am trying to change the text colour in a UITextField using the following code (RGBA value) however it just appears white, or clear, I'm not too sure as the background is white itself.
passwordTextField.textColor = UIColor(red: CGFloat(202.0), green: CGFloat(228.0), blue: CGFloat(230.0), alpha: CGFloat(100.0))
passwordTextField.returnKeyType = UIReturnKeyType.Done
passwordTextField.placeholder = "Password"
passwordTextField.backgroundColor = UIColor.clearColor()
passwordTextField.borderStyle = UITextBorderStyle.RoundedRect
passwordTextField.font = UIFont(name: "Avenir Next", size: 14)
passwordTextField.textAlignment = NSTextAlignment.Center
passwordTextField.secureTextEntry = true
RGB values for UIColor are between 0 and 1 (see the documentation "specified as a value from 0.0 to 1.0")
You need to divide your numbers by 255:
passwordTextField.textColor = UIColor(red: CGFloat(202.0/255.0), green: CGFloat(228.0/255.0), blue: CGFloat(230.0/255.0), alpha: CGFloat(1.0))
Another thing, you don't need to create CGFloats:
passwordTextField.textColor = UIColor(red:202.0/255.0, green:228.0/255.0, blue:230.0/255.0, alpha:1.0)
Using convenience init ( code like a pro )
Step 1
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
}
Usage
//let color = UIColor(red: 202/255, green: 228/255, blue: 230/255, alpha: 1) ☠️
let color = UIColor(r: 202, g: 228, b: 230) // 😍
try this instead :
passwordTextField.textColor = UIColor(red: 0.792, green: 0.894, blue: 0.901, alpha: 1.0
Always put substituted values. 202/255 = 0.792
red, green, blue and alpha are supposed to be between 0.0 and 1.0.
As others mentioned, UIColor components are normalized in the range 0.0 ~ 1.0 (I think wide color gamuts are the exception, but haven't researched that yet).
A conveninet extension to the UIColor class will let you use values in the 0~255 range (like those obtained from various inspectors and image editing tools):
import UIKit
extension UIColor {
convenience init(
redByte red:UInt8,
greenByte green:UInt8,
blueByte blue:UInt8,
alphaByte alpha:UInt8
) {
self.init(
red: CGFloat(red )/255.0,
green: CGFloat(green)/255.0,
blue: CGFloat(blue )/255.0,
alpha: CGFloat(alpha)/255.0
)
}
}
UIColor convenient methods, from Integers, or from Hex.
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
convenience init(rgb: Int, alpha: CGFloat = 1) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF,
alpha: alpha
)
}
}

How to make a random color with Swift

How I can make a random color function using Swift?
import UIKit
class ViewController: UIViewController {
var randomNumber = arc4random_uniform(20)
var randomColor = arc4random()
//Color Background randomly
func colorBackground() {
// TODO: set a random color
view.backgroundColor = UIColor.yellow
}
}
You're going to need a function to produce random CGFloats in the range 0 to 1:
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
Then you can use this to create a random colour:
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0
)
}
}
If you wanted a random alpha, just create another random number for that too.
You can now assign your view's background colour like so:
self.view.backgroundColor = .random()
For Swift 4.2
extension UIColor {
static var random: UIColor {
return UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
)
}
}
For Swift 3 and above:
extension CGFloat {
static var random: CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static var random: UIColor {
return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
}
}
Usage:
let myColor: UIColor = .random
Make a function to generate random color:
func getRandomColor() -> UIColor {
//Generate between 0 to 1
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())
return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}
Now, you can call this function whenever you need random color.
self.view.backgroundColor = getRandomColor()
For random solid colors you can use UIColor HSB initializer and randomize only the hue:
extension UIColor {
static var random: UIColor {
return .init(hue: .random(in: 0...1), saturation: 1, brightness: 1, alpha: 1)
}
}
let color1: UIColor = .random
let color2: UIColor = .random
let color3: UIColor = .random
let color4: UIColor = .random
let color5: UIColor = .random
SwiftUI - Swift 5
import SwiftUI
extension Color {
static var random: Color {
return Color(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1))
}
}
Usage:
let randomColor: Color = .random
With Swift 4.2, you can simplify this by using the new random functions which have been added:
extension UIColor {
static func random () -> UIColor {
return UIColor(
red: CGFloat.random(in: 0...1),
green: CGFloat.random(in: 0...1),
blue: CGFloat.random(in: 0...1),
alpha: 1.0)
}
}
There are more details here.
Swift 4.2 🔸
I'm adding this answer because it uses a different approach, and because many of the previous answers requires additional syntactic sugar, which in my opinion shouldn't be preferred. Vanilla Swift for the win.
extension UIColor {
/**
* Returns random color
* ## Examples:
* self.backgroundColor = UIColor.random
*/
static var random: UIColor {
let r:CGFloat = .random(in: 0...1)
let g:CGFloat = .random(in: 0...1)
let b:CGFloat = .random(in: 0...1)
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
}
Swift 4.2 Extension
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
static func random() -> UIColor {
return UIColor(rgb: Int(CGFloat(arc4random()) / CGFloat(UINT32_MAX) * 0xFFFFFF))
}
}
Usage:
let color = UIColor.random()
Swift 5.1
Make This function and generate Random color.
e.g. view.backgroundColor = random()
func random() -> UIColor {
return UIColor(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0)
}
Using an extension with an inline function to generate randoms
extension UIColor {
static func random() -> UIColor {
func random() -> CGFloat { return .random(in:0...1) }
return UIColor(red: random(),
green: random(),
blue: random(),
alpha: 1.0)
}
}
func anotherGetRandomColor()->UIColor{
let newRed = Double(arc4random_uniform(256))/255.0
let newGreen = Double(arc4random_uniform(256))/255.0
let newBlue = Double(arc4random_uniform(256))/255.0
return UIColor(red: CGFloat(newRed), green: CGFloat(newGreen), blue: CGFloat(newBlue), alpha: 1.0)
}