Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add methods to make images using a DynamicGradient #38

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Examples/DynamicColorExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@
objects = {

/* Begin PBXBuildFile section */
C56086B51F2F7C300085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086B81F2F866D0085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086B91F2F866D0085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086BA1F2F866E0085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086BB1F2F866E0085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086BC1F2F866F0085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086BD1F2F86700085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086BE1F2F86700085F569 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56086B41F2F7C300085F569 /* CGFloat.swift */; };
C56086C51F2F962D0085F569 /* angularRainbowImage.png.ref in Resources */ = {isa = PBXBuildFile; fileRef = C56086C31F2F962D0085F569 /* angularRainbowImage.png.ref */; };
C56086C61F2F962D0085F569 /* linearRainbowImage.png.ref in Resources */ = {isa = PBXBuildFile; fileRef = C56086C41F2F962D0085F569 /* linearRainbowImage.png.ref */; };
CE1BD0811DEA01E500E11D77 /* ContrastDisplayContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE1BD0801DEA01E500E11D77 /* ContrastDisplayContext.swift */; };
CE1BD0821DEA01E500E11D77 /* ContrastDisplayContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE1BD0801DEA01E500E11D77 /* ContrastDisplayContext.swift */; };
CE1BD0831DEA01E500E11D77 /* ContrastDisplayContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE1BD0801DEA01E500E11D77 /* ContrastDisplayContext.swift */; };
Expand Down Expand Up @@ -204,6 +214,9 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
C56086B41F2F7C300085F569 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
C56086C31F2F962D0085F569 /* angularRainbowImage.png.ref */ = {isa = PBXFileReference; lastKnownFileType = file; path = angularRainbowImage.png.ref; sourceTree = "<group>"; };
C56086C41F2F962D0085F569 /* linearRainbowImage.png.ref */ = {isa = PBXFileReference; lastKnownFileType = file; path = linearRainbowImage.png.ref; sourceTree = "<group>"; };
CE1BD0801DEA01E500E11D77 /* ContrastDisplayContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContrastDisplayContext.swift; sourceTree = "<group>"; };
CE4E1EFB1D818AB100D2AC35 /* DynamicGradient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DynamicGradient.swift; sourceTree = "<group>"; };
CE4E1F041D819AEC00D2AC35 /* DynamicColorSpace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DynamicColorSpace.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -351,6 +364,8 @@
CEA4D1331D95642900B12DAB /* iOSTests */ = {
isa = PBXGroup;
children = (
C56086C31F2F962D0085F569 /* angularRainbowImage.png.ref */,
C56086C41F2F962D0085F569 /* linearRainbowImage.png.ref */,
CEA4D1361D95642900B12DAB /* Info.plist */,
);
path = iOSTests;
Expand Down Expand Up @@ -426,6 +441,7 @@
CE4E1EFB1D818AB100D2AC35 /* DynamicGradient.swift */,
CEF85A241C84EA5B00DD1A49 /* HSL.swift */,
CE5D647A1D35074B005DEE4E /* Utils.swift */,
C56086B41F2F7C300085F569 /* CGFloat.swift */,
);
name = Sources;
path = ../Sources;
Expand Down Expand Up @@ -769,6 +785,8 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C56086C51F2F962D0085F569 /* angularRainbowImage.png.ref in Resources */,
C56086C61F2F962D0085F569 /* linearRainbowImage.png.ref in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -829,6 +847,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C56086B81F2F866D0085F569 /* CGFloat.swift in Sources */,
CE8688911E2C165D00207CAC /* ContrastDisplayContext.swift in Sources */,
CE8688991E2C165D00207CAC /* DynamicColor+XYZ.swift in Sources */,
CE8688951E2C165D00207CAC /* DynamicColor+HSL.swift in Sources */,
Expand All @@ -850,6 +869,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C56086B91F2F866D0085F569 /* CGFloat.swift in Sources */,
CE8688B11E2C1AF700207CAC /* ContrastDisplayContext.swift in Sources */,
CE8688B91E2C1AF700207CAC /* DynamicColor+XYZ.swift in Sources */,
CE8688B51E2C1AF700207CAC /* DynamicColor+HSL.swift in Sources */,
Expand All @@ -871,6 +891,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C56086BA1F2F866E0085F569 /* CGFloat.swift in Sources */,
CE8688CC1E2C1B4800207CAC /* ContrastDisplayContext.swift in Sources */,
CE8688D41E2C1B4800207CAC /* DynamicColor+XYZ.swift in Sources */,
CE8688D01E2C1B4800207CAC /* DynamicColor+HSL.swift in Sources */,
Expand Down Expand Up @@ -905,6 +926,7 @@
CE1BD0841DEA01E500E11D77 /* ContrastDisplayContext.swift in Sources */,
CEA4D13B1D95643E00B12DAB /* DynamicColor.swift in Sources */,
CEA4D1451D95643E00B12DAB /* HSL.swift in Sources */,
C56086BD1F2F86700085F569 /* CGFloat.swift in Sources */,
CEA4D1411D95643E00B12DAB /* DynamicColor+RGBA.swift in Sources */,
CEA4D13F1D95643E00B12DAB /* DynamicColor+Lab.swift in Sources */,
CEA4D15B1D95647000B12DAB /* DynamicColor+XYZTests.swift in Sources */,
Expand All @@ -921,6 +943,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C56086B51F2F7C300085F569 /* CGFloat.swift in Sources */,
CE5D64AD1D381782005DEE4E /* Array.swift in Sources */,
CE4E1F111D81A6D900D2AC35 /* DynamicColor+HSB.swift in Sources */,
CE4E1F0B1D819C2E00D2AC35 /* DynamicColor+Mixing.swift in Sources */,
Expand Down Expand Up @@ -955,6 +978,7 @@
CE1BD0851DEA01E500E11D77 /* ContrastDisplayContext.swift in Sources */,
CEAF67911CA2D342008DC3A2 /* DynamicColor+RGBA.swift in Sources */,
CE4E1F091D819AEC00D2AC35 /* DynamicColorSpace.swift in Sources */,
C56086BE1F2F86700085F569 /* CGFloat.swift in Sources */,
CE4E1F001D818AB100D2AC35 /* DynamicGradient.swift in Sources */,
CE4E1F0F1D819C2E00D2AC35 /* DynamicColor+Mixing.swift in Sources */,
CEA4D1631D95647000B12DAB /* DynamicColor+XYZTests.swift in Sources */,
Expand Down Expand Up @@ -985,6 +1009,7 @@
CE8B86571D2991F000C5A670 /* DynamicColor+XYZ.swift in Sources */,
CE5D64AF1D381782005DEE4E /* Array.swift in Sources */,
CEEB28D21BE27340001A74E8 /* AppDelegate.swift in Sources */,
C56086BC1F2F866F0085F569 /* CGFloat.swift in Sources */,
CE4E1EFE1D818AB100D2AC35 /* DynamicGradient.swift in Sources */,
CE4E1F131D81A6D900D2AC35 /* DynamicColor+HSB.swift in Sources */,
CE4E1F0D1D819C2E00D2AC35 /* DynamicColor+Mixing.swift in Sources */,
Expand All @@ -1010,6 +1035,7 @@
CE4E1F0C1D819C2E00D2AC35 /* DynamicColor+Mixing.swift in Sources */,
CE8B86561D2991F000C5A670 /* DynamicColor+XYZ.swift in Sources */,
CE4E1F061D819AEC00D2AC35 /* DynamicColorSpace.swift in Sources */,
C56086BB1F2F866E0085F569 /* CGFloat.swift in Sources */,
CE5D64AE1D381782005DEE4E /* Array.swift in Sources */,
CEFBDAE11B1CE38D000E6F30 /* AppDelegate.swift in Sources */,
CEF02EEE1D2984CD00D810B9 /* DynamicColor+HSL.swift in Sources */,
Expand Down
Binary file added Examples/iOSTests/angularRainbowImage.png.ref
Binary file not shown.
Binary file added Examples/iOSTests/linearRainbowImage.png.ref
Binary file not shown.
51 changes: 51 additions & 0 deletions Sources/CGFloat.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/

#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif


/**
Convenient extension for working with radiant angles DynamicGradient.
*/
public extension CGFloat {
/**
Normalize a angle in radian between [-CGFloat.pi, CGFloat.pi]
*/
public func normalizeAngle() -> CGFloat {
let result = self.truncatingRemainder(dividingBy: 2.0 * CGFloat.pi)
if result < -CGFloat.pi {
return result + 2.0 * CGFloat.pi
} else if result > CGFloat.pi {
return result - 2.0 * CGFloat.pi
}

return result
}
}
11 changes: 11 additions & 0 deletions Sources/DynamicColor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,15 @@ public extension DynamicColor {
public func isContrasting(with otherColor: DynamicColor, inContext context: ContrastDisplayContext = .standard) -> Bool {
return self.contrastRatio(with: otherColor) > context.minimumContrastRatio
}

/**
Return a boolean value which indicates if the current color is opaque.

This is a shortcut for "color.alphaComponent == 1.0"

- returns: true if this color is opaque, false otherwise
*/
public var isOpaque: Bool {
return self.alphaComponent == 1.0
}
}
153 changes: 153 additions & 0 deletions Sources/DynamicGradient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,157 @@ final public class DynamicGradient {

return color
}


/**
Return a boolean value which indicates if the current gradient is opaque, which means that all colors of this gradient are opaque.

- returns: true if this gradient is opaque, false otherwise
*/
public var isOpaque: Bool {
for color in self.colors {
if !color.isOpaque {
return false
}
}
return true
}


#if os(iOS) || os(tvOS) || os(watchOS)

/**
Create a image using this gradient as a linear gradient.

- parameter size: The size in point of the resulting image. The number of pixel depends of the scale factor of the device’s main screen.
- parameter startPoint: The start point corresponds to the first stop of the gradient. The point is defined in the unit coordinate space and is then mapped to the image’s bounds rectangle when drawn. Indicates (0.0,0.0) for top left and (1.0,1.0) for bottom right.
- parameter endPoint: The end point corresponds to the last stop of the gradient. The point is defined in the unit coordinate space and is then mapped to the image’s bounds rectangle when drawn. Indicates (0.0,0.0) for top left and (1.0,1.0) for bottom right.
- parameter nbSteps: The number of step use to mix color using given colorspace. Use default value to use an automatic number of steps. In colorspace other than rgb, bigger numbers can give more accurate results.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- returns: the created UIImage containing the gradient
*/
public func linearImage(withSize size:CGSize, startPoint:CGPoint, endPoint:CGPoint, numberOfSteps nbSteps:Int = 0, inColorSpace colorspace: DynamicColorSpace = .rgb) -> UIImage? {

let finalNbSteps:Int
if nbSteps == 0 {
if colorspace == .rgb {
//let CAGradientLayer do the job!
finalNbSteps = colors.count
} else {
//arbitrary use the size to compute a not too bad nbSteps
finalNbSteps = Int(ceil(sqrt(size.width * size.height)))
}
} else {
finalNbSteps = nbSteps
}

guard finalNbSteps > 1 else {
return nil
}

let convertedColors:[CGColor] = (0..<finalNbSteps).map {
(i) -> CGColor in
let color = self.pickColorAt(scale: CGFloat (i)/CGFloat (finalNbSteps - 1), inColorSpace: colorspace)
return color.cgColor
}

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect (origin: CGPoint.zero, size: size)
gradientLayer.colors = convertedColors
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
gradientLayer.contentsScale = UIScreen.main.scale

UIGraphicsBeginImageContextWithOptions(size, self.isOpaque, 0)

guard let context = UIGraphicsGetCurrentContext() else {
return nil
}

gradientLayer.render (in: context)

guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}

UIGraphicsEndImageContext()

return image
}


/**
Create a image using this gradient as a angular gradient.
Draw an arc using radius, startAngle, endAngle and clockwise. The center of the arcs is the center of the image. The arc is filled with "nbSteps" smaller arcs. Each smaller arc have a different interpolating color mix using the given colorspace.

- parameter size: The size in point of the resulting image. The number of pixel depends of the scale factor of the device’s main screen.
- parameter radius: Specifies the radius of the circle used to define the arc.
- parameter startAngle: Specifies the starting angle of the arc (measured in radians).
- parameter endAngle: Specifies the end angle of the arc (measured in radians).
- parameter nbSteps: The number of step use to mix color using given colorspace. Bigger numbers can give more accurate results.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- returns: the created UIImage containing the gradient
*/
public func angularImage(withSize size:CGSize, radius:CGFloat, startAngle:CGFloat, endAngle:CGFloat, clockwise:Bool, numberOfSteps nbSteps:Int = 360, inColorSpace colorspace: DynamicColorSpace = .rgb) -> UIImage? {

guard nbSteps > 1 else {
return nil
}

let center = CGPoint (x: size.width / 2.0, y: size.height / 2.0)

let convertedColors:[CGColor] = (0..<nbSteps).map {
(i) -> CGColor in
let color = self.pickColorAt(scale: CGFloat (i)/CGFloat (nbSteps - 1), inColorSpace: colorspace)
return color.cgColor
}


let normalizedStart = startAngle.normalizeAngle()
let normalizedEnd = endAngle.normalizeAngle()

var stepAngle:CGFloat
if clockwise {
stepAngle = normalizedEnd - normalizedStart
if normalizedEnd <= normalizedStart {
stepAngle = stepAngle + CGFloat.pi * 2.0
}
} else {
stepAngle = normalizedEnd - normalizedStart
if normalizedEnd >= normalizedStart {
stepAngle = stepAngle - CGFloat.pi * 2.0
}
}
stepAngle = stepAngle / CGFloat(nbSteps - 1)


UIGraphicsBeginImageContextWithOptions(size, self.isOpaque, 0)

guard let context = UIGraphicsGetCurrentContext() else {
return nil
}

for i in (1..<nbSteps) {
let color = convertedColors[i]

let bezierPath = UIBezierPath(arcCenter:center, radius:radius, startAngle:CGFloat(i) * stepAngle + normalizedStart, endAngle:CGFloat(i + 1) * stepAngle + normalizedStart, clockwise:clockwise)
bezierPath.addLine(to: center)
bezierPath.close()

context.setFillColor(color)
context.setStrokeColor(color)
bezierPath.fill()
bezierPath.stroke()
}

guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}

UIGraphicsEndImageContext()

return image
}

#endif
}
49 changes: 49 additions & 0 deletions Tests/DynamicGradientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,53 @@ class DynamicGradientTests: XCTestCase {

XCTAssert(darkYellow.toHex() == 0x808000, "Color should be a dark yellow (not \(darkYellow.toHexString()))")
}

#if os(iOS) || os(tvOS) || os(watchOS)

func testLinearImage() {
let rainbow = [.red, .green, .blue, .red].gradient

let linearRainbowImage = rainbow.linearImage(withSize: CGSize(width:100, height:100), startPoint: CGPoint.zero, endPoint: CGPoint(x: 1.0, y: 1.0), inColorSpace:.hsl)

XCTAssertNotNil(linearRainbowImage, "Rainbow should produce an linear image")

let linearData = UIImagePNGRepresentation(linearRainbowImage!)
XCTAssertNotNil(linearData, "Linear image should produce PNG datas")
//try? linearData?.write(to: URL(fileURLWithPath: "/tmp/linearRainbowImage.png"))

let bundle = Bundle(for: type(of: self))
guard let refLinearUrl = bundle.url(forResource: "linearRainbowImage.png", withExtension: "ref"),
let refLinearData = try? Data(contentsOf: refLinearUrl) else {
XCTFail("Ref linear image should exists")
return
}

XCTAssert(linearData! == refLinearData, "Linear image should be similar to reference")
}


func testAngularImage() {
let rainbow = [.red, .green, .blue, .red].gradient

let angularRainbowImage = rainbow.angularImage(withSize: CGSize(width:100, height:100), radius: 50, startAngle: 0, endAngle: 0, clockwise: true, inColorSpace:.hsl)

XCTAssertNotNil(angularRainbowImage, "Rainbow should produce an angular image")

let angularData = UIImagePNGRepresentation(angularRainbowImage!)
XCTAssertNotNil(angularData, "Angular image should produce PNG datas")
//try? angularData?.write(to: URL(fileURLWithPath: "/tmp/angularRainbowImage.png"))

let bundle = Bundle(for: type(of: self))
guard let refAngularUrl = bundle.url(forResource: "angularRainbowImage.png", withExtension: "ref"),
let refAngularData = try? Data(contentsOf: refAngularUrl) else {
XCTFail("Ref angular image should exists")
return
}

XCTAssert(angularData! == refAngularData, "Angular image should be similar to reference")
}



#endif
}