set UIslider thumb image in swift

2020-08-09 04:14发布

问题:

I want to set thumb of like musi app here is ss

I want

I have

Here is code

        durationSlider.setThumbImage(UIImage(named: "Slider_indicator.png"), forState: UIControlState.Normal)
    durationSlider.setThumbImage(UIImage(named: "Slider_indicator.png"), forState: UIControlState.Highlighted)

回答1:

If you want to clip the top part of the thumbImage, you should use:

public func thumbRectForBounds(bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect

So add this to your code:

durationSlider.thumbRectForBounds(...)

And set the CGRect of the thumbRect to have the value of durationSlider.frame.origin.y as its own origin.y.

Here's another temporary solution, I'll get back to the thumbRectForBounds method shortly:

let mask = CAGradientLayer(layer: durationSlider.layer)
let lineTop = (durationSlider.bounds.height/2 - 0.5) / durationSlider.bounds.height
mask.frame = durationSlider.bounds
mask.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
mask.locations = [lineTop, lineTop]
durationSlider.layer.mask = mask


回答2:

here you want to show only below part of the thumb now. so you need to make above half image clear. Please check the image i have attached with the answer

[slider setThumbImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];

Try this and download scale the image if you need