CopyPastor

Detecting plagiarism made easy.

Score: 1; Reported for: Exact paragraph match Open both answers

Possible Plagiarism

Plagiarized on 2023-10-24
by wzso

Original Post

Original - Posted on 2021-06-02
by Patrick\_K



            
Present in both answers; Present only in the new answer; Present only in the old answer;

[A clean extension by Marco Eidinger](https://blog.eidinger.info/from-hex-to-color-and-back-in-swiftui) for SwiftUI:
Hex to `Color`:
```swift import SwiftUI
extension Color { init?(hex: String) { var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines) hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt64 = 0
var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 1.0
let length = hexSanitized.count
guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { return nil }
if length == 6 { r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0 g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0 b = CGFloat(rgb & 0x0000FF) / 255.0
} else if length == 8 { r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0 g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0 b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0 a = CGFloat(rgb & 0x000000FF) / 255.0
} else { return nil }
self.init(red: r, green: g, blue: b, opacity: a) } }
```
`Color` to hex:
```swift import SwiftUI import UIKit
extension Color { func toHex() -> String? { let uic = UIColor(self) guard let components = uic.cgColor.components, components.count >= 3 else { return nil } let r = Float(components[0]) let g = Float(components[1]) let b = Float(components[2]) var a = Float(1.0)
if components.count >= 4 { a = Float(components[3]) }
if a != Float(1.0) { return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255)) } else { return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255)) } } }
```
I also used the solution for `UIColor` by hackingwithswift. This is an adapted version for `Color`:
init?(hex: String) { var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines) hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt64 = 0
var red: Double = 0.0 var green: Double = 0.0 var blue: Double = 0.0 var opacity: Double = 1.0
let length = hexSanitized.count
guard Scanner(string: hexSanitized).scanHexInt64(&rgb) else { return nil }
if length == 6 { red = Double((rgb & 0xFF0000) >> 16) / 255.0 green = Double((rgb & 0x00FF00) >> 8) / 255.0 blue = Double(rgb & 0x0000FF) / 255.0
} else if length == 8 { red = Double((rgb & 0xFF000000) >> 24) / 255.0 green = Double((rgb & 0x00FF0000) >> 16) / 255.0 blue = Double((rgb & 0x0000FF00) >> 8) / 255.0 opacity = Double(rgb & 0x000000FF) / 255.0
} else { return nil }
self.init(.sRGB, red: red, green: green, blue: blue, opacity: opacity) }


        
Present in both answers; Present only in the new answer; Present only in the old answer;