سؤال

So I've got a UISlider that I've been working on and I need it to have a custom image. I've got a nice @2x image which has a great amount of pixels and looks great when I add it to a UIImageView, but the moment I use the same image for a replacement for the UISlider thumb image, it pixelates the heck out of it and makes the thumb of the slider look like crap. Any thoughts on how to remedy this?

Here is some of my sample code.

 slider = [[UISlider alloc] initWithFrame:CGRectMake(sliderOffset, 29.5, siderW, 50)];
    [slider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    [slider setBackgroundColor:[UIColor clearColor];
    slider.minimumValue = 0.0;
    slider.maximumValue = 10000.0;
    slider.continuous = YES;
    slider.value = 3000.00;
    [slider setThumbImage:[UIImage imageNamed:@"Slider@2x.png"] forState:UIControlStateNormal];
    [slider setThumbImage:[UIImage imageNamed:@"Slider@2x.png"] forState:UIControlStateHighlighted];

Thanks in advance!

هل كانت مفيدة؟

المحلول

Here's how I solved it:

1) Subclassed UISlider

2) Created a clear image and set the slider thumb to that clear image.

[self setThumbImage:[UIImage imageNamed:@"ClearImageForOverride.png"] forState:UIControlStateNormal];
    [self setThumbImage:[UIImage imageNamed:@"ClearImageForOverride.png"] forState:UIControlStateHighlighted];

3) Created a UIImageView and made that follow the center of the thumb.

float imageWH = PassedInHeightWidthFromSubClass;
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, imageWH, imageWH)];
imageView.image = [UIImage imageNamed:@"NewThumbImage"];
[self addSubview:imageView];
[self bringSubviewToFront:imageView];

imageView.center = CGPointMake(thumbRect.origin.x + self.frame.origin.x + localImageViewCenter,  self.frame.origin.y - sliderImageViewYOffset);
[self addTarget:self action:@selector(sliderValueChanged) forControlEvents:UIControlEventValueChanged];

4) Then when the sider value changes I tell the imageView where it's center should be.

-(void)sliderValueChanged {
    CGRect trackRect = [self trackRectForBounds:self.bounds];
    CGRect thumbRect = [self thumbRectForBounds:self.bounds trackRect:trackRect value:self.value];
    imageView.center = CGPointMake(thumbRect.origin.x + self.frame.origin.x + localImageViewCenter,  self.frame.origin.y - sliderImageViewYOffset);
}

Essentially with this you can have any size of image for the slider knob which looks great and works flawlessly as the knob.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top