Change the size of a UISlider thumbImage

2019-04-14 03:13发布

How can I change the size of a UIImage that I am using as a thumbImage. The code I use to set the image is as follows.

let image: UIImage = UIImage(assetIdentifier: UIImage.AssetIdentifier.Slider)

I use an Enum to get the image, no problem there.

The code I use to set the thumbImage is as follows.

self.setThumbImage(image, forState: UIControlState.Normal)

I have tried using the code below to change the thumb images size but cannot find the solution.

let trackRect: CGRect = CGRect(x: 0.0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
let thumbRect: CGRect = CGRect(x: 0.0, y: 0.0, width: 12.0, height: 12.0)
thumbRectForBounds(thumbRect, trackRect: trackRect, value: 0.0)

The image is currently about 40pt by 40pt (Its a circle). I would like the image to be around 24pt by 24pt.

Also, this is in Swift 2 on XCode 7. I understand those methods are for iOS8.0 or above and that is my deployment target.

1条回答
一夜七次
2楼-- · 2019-04-14 03:35

The thumb will be the size of the image you provide. To get a 24pt by 24pt thumb, you must provide 48px by 48px (and 72x72 for @3) image. This also affects the slider frame.

You can define an extension to resize images on the fly if needed:

extension UIImage
{
    func imageWithImage(image: UIImage, scaledToSize newSize: CGSize) -> UIImage
    {    
         UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
         image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))

         let newImage = UIGraphicsGetImageFromCurrentImageContext()    
         UIGraphicsEndImageContext()

         return newImage;
    }
}

That way you can even do cool stuff like have a slider where the thumb grows and shrinks, as it approaches max and min values.

查看更多
登录 后发表回答