[英]Swift: How can I change the size of Thumb Image on UISlider based of the value of the slider?
I haven't found an answer for this in Swift.我在 Swift 中没有找到答案。
I have a UISlider that changes the value of a brush size for a drawing app I'm making.我有一个 UISlider 可以更改我正在制作的绘图应用程序的画笔大小的值。 I want the size of the thumb image to update depending on the value of the slider's thumb position.我希望根据滑块拇指 position 的值更新拇指图像的大小。
Here's a screenshot of the slider for some context:这是 slider 的屏幕截图,用于某些上下文:
I set the initial image of the thumb in viewDidLoad()我在 viewDidLoad() 中设置了拇指的初始图像
self.brushSizeSlider.setThumbImage(UIImage(named: "black"), forState: UIControlState.Normal)
and have an IBAction for the slider as follows:并为 slider 设置 IBAction,如下所示:
@IBAction func brushSizeSliderChanged(sender: UISlider) {
if sender == brushSizeSlider {
self.brushWidth = CGFloat(sender.value)
println("the size of the brush is: \(self.brushWidth)")
}
}
What should I add to brushSizeSliderChanged
to change the size of it's thumb image depending on the value of brushSizeSliders thumb position / value?我应该添加什么到brushSizeSliderChanged
以根据brushSizeSliders thumb position / 值的值更改其拇指图像的大小?
var ratio : CGFloat = CGFloat ( sender.value + 0.5)
var thumbImage : UIImage = UIImage(named: "yourImage")!
var size = CGSizeMake( thumbImage.size.width * ratio, thumbImage.size.height * ratio )
self.setThumbImage( self.imageWithImage(thumbImage, scaledToSize: size), forState: UIControlState.Normal )
Add this code to your action method将此代码添加到您的操作方法
You can use a more recent API您可以使用更新的 API
extension UIImage {
/// Непропорциональное масштабирование к указанному размеру
/// - Parameter size: конечный размер изображения
/// - Parameter displayScale: масштаб, в котором создаётся итоговое изображение
/// - Returns: изображение необходимого размера
func scaled(to size: CGSize, scale displayScale: CGFloat = UIScreen.main.scale) -> UIImage {
let format = UIGraphicsImageRendererFormat.preferred()
format.scale = displayScale
return UIGraphicsImageRenderer(size: size, format: format).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.