我有这种类型的自定义UISlider
我实现了如下所示:
它的特殊之处在于你无法将它拖到它的初始拇指位置的左侧。
但是当你将它向右拖动时,它应该像这样改变路径的颜色,将颜色留在原来的位置并着色它所经过的路径:
我只知道UISlider
- MinimumTrackImage
和MaximumTrackImage
的两个属性,它们负责句柄的右侧和左侧。
如何实现这种奇怪的行为?有任何想法吗?谢谢!
答案 0 :(得分:1)
我能够使用以下代码实现此功能。要弄清楚的棘手部分是如何根据滑块的起始值设置初始图像。我通过创建一个4像素宽的图像来做到这一点,左边的2个像素是你的开始左边的颜色,右边的2个像素是你想要的拖动后的颜色。基本上,我拉伸该图像(仅在左侧)以填充图像视图,然后使用UIGraphicsGetImageFromCurrentImageContext()获取该图像。然后,我创建了另一个可伸缩的图像,该图像仅在右侧拉伸。
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (weak,nonatomic) IBOutlet UISlider *slider;
@property (nonatomic) CGFloat previousValue;
@end
@implementation ViewController
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.previousValue = self.slider.value;
if (self.slider.value > .01) {
UIImage *newImage = [self imageStretchedOnLeft];
UIImage *rightStretchImage = [newImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, newImage.size.width -2, 0, 0) resizingMode:UIImageResizingModeStretch];
[self.slider setMinimumTrackImage:rightStretchImage forState:UIControlStateNormal];
}else{
[self.slider setMinimumTrackImage:[UIImage imageNamed:@"OneColor.png"] forState:UIControlStateNormal];
}
}
-(IBAction)sliderMoved:(UISlider *)slider {
if (slider.value < self.previousValue) {
slider.value = self.previousValue;
}
self.previousValue = slider.value;
}
- (UIImage *)imageStretchedOnLeft {
UIImage *image = [UIImage imageNamed:@"TwoColor.png"]; // 4 pixel wide 1 pixel high image. Left 2 pixels are original track color, right two are new drag color
UIImage *cappedImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 2)];
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.slider.frame.size.width * (self.slider.value/self.slider.maximumValue), self.slider.frame.size.height)];
iv.image = cappedImage;
[self.view insertSubview:iv belowSubview:self.view];
UIGraphicsBeginImageContextWithOptions(iv.frame.size, YES, [[UIScreen mainScreen] scale]);
[iv.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[iv removeFromSuperview];
return img;
}
如果滑块的值为0,则会出现图形上下文错误,因此如果该值小于.01,则viewDidAppear方法中的if语句使用不同的一个彩色图像。
答案 1 :(得分:-1)
您可以使用此
//code for slider
UIImage *minImage = [[UIImage imageNamed:@"slider_minimum.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
UIImage *maxImage = [[UIImage imageNamed:@"slider_maximum.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
UIImage *thumbImage = [UIImage imageNamed:@"thumb.png"];
[[UISlider appearance] setMaximumTrackImage:maxImage forState:UIControlStateNormal];
[[UISlider appearance] setMinimumTrackImage:minImage forState:UIControlStateNormal];
[[UISlider appearance] setThumbImage:thumbImage forState:UIControlStateNormal];
这是raywenderlich
的好tutorial