Hossein Maktoobian Hossein Maktoobian - 20 days ago 5
Objective-C Question

How to add a gradient tint color to a UISlider in XCode 6?

I'm working on a design application that has a section for selecting colors by three sliders for RGB.
As we can see in xcode, where we want to select a color by RGB values, the slider tint color is a gradient color that changes when we change the sliders. I want to use this in my application. but I have no idea about how to do this?

I've found this code in a blog. but didn't work for me.

- (void)setGradientToSlider:(UISlider *)Slider WithColors:(NSArray *)Colors{

UIView * view = (UIView *)[[Slider subviews]objectAtIndex:0];

UIImageView * maxTrackImageView = (UIImageView *)[[view subviews]objectAtIndex:0];

CAGradientLayer * maxTrackGradient = [CAGradientLayer layer];
CGRect rect = maxTrackImageView.frame;
rect.origin.x = view.frame.origin.x;

maxTrackGradient.frame = rect;
maxTrackGradient.colors = Colors;

[maxTrackGradient setStartPoint:CGPointMake(0.0, 0.5)];
[maxTrackGradient setEndPoint:CGPointMake(1.0, 0.5)];

[[maxTrackImageView layer] insertSublayer:maxTrackGradient atIndex:0];

/////////////////////////////////////////////////////

UIImageView * minTrackImageView = (UIImageView *)[[view subviews]objectAtIndex:1];

CAGradientLayer * minTrackGradient = [CAGradientLayer layer];
rect = minTrackImageView.frame;
rect.size.width = maxTrackImageView.frame.size.width;
rect.origin.x = 0;
rect.origin.y = 0;

minTrackGradient.frame = rect;
minTrackGradient.colors = Colors;

[minTrackGradient setStartPoint:CGPointMake(0.0, 0.5)];
[minTrackGradient setEndPoint:CGPointMake(1.0, 0.5)];

[minTrackImageView.layer insertSublayer:minTrackGradient atIndex:0];

}


I would appreciate any helps. Thanks.

Answer

This is a really effective approach that I've found after a lot of web search. So it's better to share it here as a complete answer. The following code is a Swift Class That you can use to create and use gradients as UIView or UIImage.

import Foundation
import UIKit

class Gradient: UIView{
    // Gradient Color Array
    private var Colors: [UIColor] = []

    // Start And End Points Of Linear Gradient
    private var SP: CGPoint = CGPoint.zeroPoint
    private var EP: CGPoint = CGPoint.zeroPoint

    // Start And End Center Of Radial Gradient
    private var SC: CGPoint = CGPoint.zeroPoint
    private var EC: CGPoint = CGPoint.zeroPoint

    // Start And End Radius Of Radial Gradient
    private var SR: CGFloat = 0.0
    private var ER: CGFloat = 0.0

    // Flag To Specify If The Gradient Is Radial Or Linear
    private var flag: Bool = false

    // Some Overrided Init Methods
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    // Draw Rect Method To Draw The Graphics On The Context
    override func drawRect(rect: CGRect) {
        // Get Context
        let context = UIGraphicsGetCurrentContext()

        // Get Color Space
        let colorSpace = CGColorSpaceCreateDeviceRGB()

        // Create Arrays To Convert The UIColor to CG Color
        var colorComponent: [CGColor] = []
        var colorLocations: [CGFloat] = []
        var i: CGFloat = 0.0

        // Add Colors Into The Color Components And Use An Index Variable For Their Location In The Array [The Location Is From 0.0 To 1.0]
        for color in Colors {
            colorComponent.append(color.CGColor)
            colorLocations.append(i)
            i += CGFloat(1.0) / CGFloat(self.Colors.count - 1)
        }

        // Create The Gradient With The Colors And Locations
        let gradient: CGGradientRef = CGGradientCreateWithColors(colorSpace, colorComponent, colorLocations)

        // Create The Suitable Gradient Based On Desired Type
        if flag {
            CGContextDrawRadialGradient(context, gradient, SC, SR, EC, ER, 0)
        } else {
            CGContextDrawLinearGradient(context, gradient, SP, EP, 0)
        }
    }

    // Get The Input Data For Linear Gradient
    func CreateLinearGradient(startPoint: CGPoint, endPoint: CGPoint, colors: UIColor...) {
        self.Colors = colors
        self.SP = startPoint
        self.EP = endPoint
        self.flag = false
    }

    // Get The Input Data For Radial Gradient
    func CreateRadialGradient(startCenter: CGPoint, startRadius: CGFloat, endCenter: CGPoint, endRadius: CGFloat, colors: UIColor...) {
        self.Colors = colors
        self.SC = startCenter
        self.EC = endCenter
        self.SR = startRadius
        self.ER = endRadius
        self.flag = true
    }

    // Function To Convert Gradient To UIImage And Return It
    func getImage() -> UIImage {
        // Begin Image Context
        UIGraphicsBeginImageContext(self.bounds.size)

        // Draw The Gradient
        self.drawRect(self.frame)

        // Get Image From The Current Context
        let image = UIGraphicsGetImageFromCurrentImageContext()

        // End Image Context
        UIGraphicsEndImageContext()

        // Return The Result Gradient As UIImage
        return image
    }
}