如何在圆圈中动态排列图像

时间:2012-09-24 09:43:13

标签: iphone ios xcode geometry

如何在圆形图像中动态排列图标(UIButtons,带背景图像)。它应该像同心圆一样。

我使用以下代码,

UIImageView *container = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0f, 299.0f, 298.0f)];
    container.image = [UIImage imageNamed:@"AR_RF004_circle.png"];
    container.center = CGPointMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0);
    [self.view addSubview:container];

    NSArray *imagesArray = [[NSArray alloc]initWithObjects:[UIImage imageNamed:@"AR1.png"],[UIImage imageNamed:@"AR2.png"],[UIImage imageNamed:@"AR3.png"],[UIImage imageNamed:@"AR4.png"],[UIImage imageNamed:@"AR5.png"], nil];
int numberOfSections = 5;
    CGFloat angleSize = 2*M_PI/numberOfSections;
for (int j = 0; j < numberOfSections; ++j) {
        UIButton *sectionLabel = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 150.0f, 128.0f)];
[sectionLabel setBackgroundImage:[imagesArray objectAtIndex:j] forState:UIControlStateNormal];
sectionLabel.layer.anchorPoint = CGPointMake(0.9f, 0.1f);
        sectionLabel.layer.position = CGPointMake(container.bounds.size.width/2.0, container.bounds.size.height/2.0); // places anchorPoint of each label directly in the center of the circle.

        sectionLabel.transform = CGAffineTransformMakeRotation(angleSize*j);
        [container addSubview:sectionLabel];
    NSLog(@"section label x and y is %f ,%f",sectionLabel.frame.origin.x,sectionLabel.frame.origin.y);
    }
    [container release];

先谢谢

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码:

UIButton *currentButton;
int buttonCount = 20;
int radius = 200; 
float angleBetweenButtons = (2 * M_PI) / buttonCount;
float x = 0;
float y = 0;
CGAffineTransform rotationTransform;

for (int i = 0; i < buttonCount; i++)
{
    // get your button from array or something
    currentButton = ...
    ...

    x = radius + cosf(i * angleBetweenButtons) * radius;
    y = radius + sinf(i * angleBetweenButtons) * radius;
    rotationTransform = CGAffineTransformIdentity;
    rotationTransform = CGAffineTransformRotate(rotationTransform, (i * angleBetweenButtons));
    currentButton.center = CGPointMake(x, y);
    currentButton.transform = rotationTransform;
}

答案 1 :(得分:1)

我认为你可以做这样的事情

sectionLabel.center = container.center;

我还没有检查过其他代码..最简单的方法