简体   繁体   中英

how to increase and decrease circle size in uislider with value change

I want to increase and decrease a circle size in uislider with value change..

here my code

draw.m

- (id)initWithFrame:(CGRect)frame value:(float )x
{
    value=x;
    self = [super initWithFrame:frame];
    if (self) {

    }
   return self;
 }

- (void)drawRect:(CGRect)rect{

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGRect rectangle = CGRectMake(6,17,value,value);
CGContextAddEllipseInRect(context, rectangle);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillPath(context);

}

and ViewController.m

@implementation ViewController
 @synthesize mySlider,colorLabel;

 - (void)viewDidLoad
  {    [super viewDidLoad];
  }

  - (void)didReceiveMemoryWarning
 {
 [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
 -(IBAction)sliderValue:(UISlider*)sender
{

float r=[[NSString stringWithFormat:@"%.0f",mySlider.value] floatValue];
NSLog(@"value...%f",r);
CGRect positionFrame = CGRectMake(10,100,200,100);
circle = [[draw alloc] initWithFrame:positionFrame value:r];
circle.backgroundColor=[UIColor clearColor];
[self.view addSubview:circle];


 }

in this code, circle size has increase but not decrease and another problem is circle look , output is .

在此处输入图片说明

Ok, your code works, it just doesn't look like it. Add

[circle removeFromSuperview];
circle = nil;

right above

circle = [[draw alloc] initWithFrame:positionFrame value:r];

You keep drawing new circles on top of the previous ones so it takes that odd shape and also doesn't look like it's decreasing.

EDIT

To redraw your circle instead of creating a new one everytime, as @Larme pointed out, you would have to change your 'draw' object to contain a public method which reassigns your 'draw' circle objects diameter.

-(void) setDiameterWithFloat: (float)x{

    value = x;

}

Then in your sliderValue IBAction, call this new method to assign the new diameter based on your slider and redraw the circle with setNeedsDisplay :

[circle setDiameterWithFloat:mySlider.value];
[circle setNeedsDisplay];

This allows you to move your initialization of the object to viewDidLoad in your ViewController, where it will be created and loaded only one time along with the rest of the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM