[英]Customize UISLider to change the color after the thumb is dragged
我已經實現了這種類型的自定義UISlider
,如下所示:
它的獨特之處在於您不能將其拖到初始拇指位置的左側。
但是,當您將其拖動到右側時,它應該像這樣更改路徑的顏色,而將顏色保留在左側,並為它行進的路徑着色:
我只知道UISlider
的兩個屬性MinimumTrackImage
和MaximumTrackImage
,它們分別負責手柄的右側和左側。
如何實現這種奇怪的行為? 有任何想法嗎? 謝謝!
我可以使用以下代碼來實現。 要弄清楚的棘手部分是如何根據滑塊的起始值設置初始圖像。 我通過創建一個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語句將使用另一幅彩色圖像。
你可以用這個
//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的不錯的教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.