2

I'm trying to resize UISlider thumb in iOS7 but I can't. I know that can use setThumbImage but I don't want use any images.

setThumbImage:[UIImage imageNamed:@"sliderThumb.png"]

I want to change size and color of UISlider thumb without image. can I do this?

Jamie Taylor
  • 4,709
  • 5
  • 44
  • 66
Hossein
  • 3,755
  • 2
  • 29
  • 39
  • 1
    Check this post: http://stackoverflow.com/questions/18983726/uislider-thumbtintcolor-doesnt-change-on-ios-7-fine-on-ios-6, it can help you ;) – Lapinou Apr 02 '14 at 15:07
  • Color changed successfully, now my only question is: how to resize thumb? :) – Hossein Apr 02 '14 at 15:21
  • 1
    Check this post: http://stackoverflow.com/questions/11221966/how-to-change-size-of-thumb-image-of-uislider-programmatically, if you can't resize without using a thumb image, you can use a transparant image, then you can resize the thumb and change the color like you want. – Lapinou Apr 02 '14 at 15:29

1 Answers1

2

The SWIFT code below enables you to easily change the size and color of a slider thumb:

override func viewDidLoad(){
    super.viewDidLoad()
    self.updateSlider(self.mySlider, thumbSize: 16, color: UIColor.redColor())
}

func updateSlider(slider: UISlider, thumbSize: CGFloat, color: UIColor){
    let thumbImage = createThumbImage(thumbSize, color: color)
    slider.setThumbImage(thumbImage, forState: UIControlState.Normal)
    slider.setThumbImage(thumbImage, forState: UIControlState.Highlighted)
}

func createThumbImage(size: CGFloat, color: UIColor) -> UIImage {
    let layerFrame = CGRectMake(0, 0, size, size)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = CGPathCreateWithEllipseInRect(layerFrame.insetBy(dx: 1, dy: 1), nil)
    shapeLayer.fillColor = color.CGColor
    shapeLayer.strokeColor = color.colorWithAlphaComponent(0.65).CGColor

    let layer = CALayer.init()
    layer.frame = layerFrame
    layer.addSublayer(shapeLayer)
    return self.imageFromLayer(layer)
}

func imageFromLayer(layer: CALayer) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, UIScreen.mainScreen().scale)
    layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage
}
Vegard
  • 4,352
  • 1
  • 27
  • 25