Круговое вращение пяти кнопок на одинаковом расстоянии

Я хочу повернуть пять кнопок по окружности круга (круг с центром (120,120), который на самом деле является центром квадратного вида, т.е. 240 * 240) с радиусом 100. Возможно ли это сделать, взаимодействуя с кнопками которые вращаются и надлежащий вид.

я пытался '

x =  round(cx + redious * cos(angl));
y =  round(cy - redious * sin(angl));   

NSString *X=[NSString stringWithFormat:@"%f",x];
[xval addObject:[NSString stringWithFormat:@"%@",X]];
NSString *Y=[NSString stringWithFormat:@"%f",y];
[yval addObject:[NSString stringWithFormat:@"%@",Y]];'

для подсчета баллов и:

map.frame= CGRectMake([[fqx objectAtIndex:counter1]intValue],[[fqy objectAtIndex:counter1]intValue], 72, 37);   
website.frame= CGRectMake([[fqx objectAtIndex:counter2]intValue],[[fqy objectAtIndex:counter2]intValue], 72, 37);   
share.frame= CGRectMake([[fqx objectAtIndex:counter3]intValue],[[fqy objectAtIndex:counter3]intValue], 72, 37); 
slideShow.frame= CGRectMake([[fqx objectAtIndex:counter4]intValue],[[fqy objectAtIndex:counter4]intValue], 72, 37);' 

вращаться, но он создает странный путь .. треугольным способом .. («карта», «поделиться», «слайд-шоу», «веб-сайт») или мои кнопки .. : P


person rptwsthi    schedule 25.03.2011    source источник
comment
Ваш угол радиальный? Должно быть. радУгл = угол / 180 * Пи. Также: не основывайте следующую итерацию на предыдущих координатах. Только увеличивайте угол и вычисляйте положение, используя исходное положение.   -  person Krumelur    schedule 25.03.2011
comment
нет, это угол, который я уменьшаю на единицу   -  person rptwsthi    schedule 25.03.2011
comment
@vladimir: расскажи, как ты это сделал?.. :)   -  person rptwsthi    schedule 25.03.2011
comment
@rptwsthi, выберите свой код и нажмите кнопку «{}» в редакторе вопросов. Или просто отступ строки кода с 4 пробелами   -  person Vladimir    schedule 25.03.2011
comment
Сделал что? Я не реализовал такую ​​​​вещь, поэтому нет ответа, но намек в комментарии. Я думаю, вам придется сначала покопаться в математике.   -  person Krumelur    schedule 25.03.2011
comment
@Krumelur: хорошо .. я просто просил сделать мой вопрос / ответ лучше в будущем ..   -  person rptwsthi    schedule 26.03.2011


Ответы (1)


Это было слишком мило, чтобы пройти мимо, так что вот оно. Этот код ограничен вращением одной кнопки, но я сомневаюсь, что у вас возникнут проблемы с расширением его для использования нескольких (подсказка: используйте ONE CADisplayLink и вращайте все кнопки одновременно).

- (void)setupRotatingButtons
{
    // call this method once; make sure "self.view" is not nil or the button 
    // won't appear. the below variables are needed in the @interface.
    // center: the center of rotation
    // radius: the radius
    // time:   a CGFloat that determines where in the cycle the button is located at
    //         (note: it will keep increasing indefinitely; you need to use 
    //         modulus to find a meaningful value for the current position, if
    //         needed)
    // speed:  the speed of the rotation, where 2 * M_PI is 1 lap a second
    // b:      the UIButton
    center = CGPointMake(100, 100);
    radius = 100;
    time = 0;
    speed = 2 * M_PI; // <-- will rotate CW 360 degrees per second (1 "lap"/s)

    b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    b.titleLabel.text = @"Hi";
    b.frame = CGRectMake(0.f, 0.f, 100, 50);
    // we get the center set right before we add subview, to avoid glitch at start
    [self continueCircling:nil]; 
    [self.view addSubview:b];
    [self.view bringSubviewToFront:b];
    CADisplayLink *dl = [CADisplayLink displayLinkWithTarget:self 
        selector:@selector(continueCircling:)];
    [dl addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

Нам также нужен фактический метод «continueCircling:», который просто:

- (void)continueCircling:(CADisplayLink *)dl
{
    time += speed * dl.duration;
    b.center = CGPointMake(center.x + radius * cosf(time), 
                           center.y + radius * sinf(time));
}

Я уверен, что есть другие более изящные способы решить эту проблему, но, по крайней мере, вышеизложенное работает. :)

Редактировать: я забыл упомянуть, вам нужно будет добавить платформу QuartzCore и

#import <QuartzCore/QuartzCore.h> 

для CADisplayLink.

Изменить 2: найдена константа PI (M_PI), поэтому заменено 3,1415 на нее.

person Kalle    schedule 25.03.2011
comment
Да вроде должно работать. Если вы хотите равное расстояние, вы хотите, чтобы каждый шаг между ними был делителем 2 * PI. Я уверен, что PI как константа доступна где-то там, но использование 3.1415, вероятно, достаточно близко. - person Kalle; 26.03.2011
comment
эй, что я сделал для оставшихся 4: c.center = CGPointMake(center.x + radius * cosf(time+1.3), center.y + radius * sinf(time+1.3));' d.center = CGPointMake(center.x + radius * cosf(time+2.6), center.y + radius * sinf(time+2.6)); e.center = CGPointMake(center.x + radius * cosf(time+3.9), center.y + radius * sinf(time+3.9)); f.center = CGPointMake(center.x + radius * cosf(time+5.2), center.y + radius * sinf(time+5.2)); - person rptwsthi; 07.12.2011