简体   繁体   English

如何通过更改值来增大和减小uislider中的圆圈大小

[英]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.. 我想通过更改值来增大和减小uislider中的圆圈大小。

here my code 这是我的代码

draw.m 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 和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. 要重绘您的圆,而不是每次都创建一个新的圆,就像@Larme指出的那样,您将必须更改“绘制”对象以包含一个公共方法,该方法可以重新分配“绘制”圆对象的直径。

-(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 : 然后在您的sliderValue IBAction中,调用此新方法以根据您的滑块分配新直径,并使用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. 这使您可以将对象的初始化移动到ViewController中的viewDidLoad在该对象中,对象的创建和加载将与视图的其余部分一起被加载一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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