以编程方式在圆形图像上创建UIButtons

5

我需要创建弧形的 UIButtons,并放置在一个圆形图像上(输出结果需要呈现同心圆形)。

目前我正在使用 5 张图片,但将来可能会添加更多的图片,所以我需要动态地填充圆形图像。

我有一段示例代码,输出结果如下图所示:

int numberOfSections = 6;
    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, 2.0f)];
sectionLabel.backgroundColor = [UIColor redColor];
 sectionLabel.layer.anchorPoint = CGPointMake(1.0f, 0.5f);
        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];
    }

Above Code的图片

我已经尝试使用这段代码,输出结果如下图所示:

 int numberOfSections = 5;
    CGFloat angleSize = 2*M_PI/numberOfSections;
    for (int j = 0; j<numberOfSections; ++j) {
        UIImage *imageframe = [imagesArray objectAtIndex:j];
OBShapedButton *button = [[OBShapedButton alloc] initWithFrame:CGRectMake(0.0f, 150.0f, 150.0f, 128.0f)];
button.transform = CGAffineTransformMakeRotation(angleSize*j);
[container addSubview:button];
}

第二张图片

我需要输出以下图片:

第三张图片

如何实现?

我试过了Sarah Zuo的代码,但输出不符合要求。

Sarah Zuo 代码

需要同样宽度和高度的按钮:

Sarah Zuo 代码第二种答案
非常感谢您的帮助。


新的图片会被添加到同一个圆中,从而减小现有ImageView的弧度吗? - AppleDelegate
@AppleDelegate:是的,我们会提供图像数量,这样就可以进行除法运算了。 - Srinivas
4个回答

4

我只能回答最后一部分。

如果您能获取按钮的图像,则可以参考这个教程。这可能会对你有所帮助,前提是您所制作的图像具有透明背景。


@CrazyCreator:我只是放置按钮背景图片,但如何将按钮变成圆形? - Srinivas
你永远无法创建一个圆形的按钮,这是你需要的技巧。保持其他部分透明,你的按钮就会看起来像圆形。 - DivineDesert

2
float radius = container.bounds.size.width / 2;
int numberOfSections = 5;
CGFloat angleSize = 2*M_PI/numberOfSections;
for (int j = 0; j<numberOfSections; ++j) {
    UIImage *imageframe = [imagesArray objectAtIndex:j];
    OBShapedButton *button = [[OBShapedButton alloc] initWithFrame:CGRectMake(0.0f, 150.0f, 150.0f, 128.0f)];

    button.transform = CGAffineTransformMakeRotation(2*M_PI-angleSize*j);
    button.center = CGPointMake(radius + radius * sin(angleSize * j) / 2, radius +  radius * cos(angleSize * j) / 2);
    [container addSubview:button];
}

尝试这段代码。


现在当我使用您的代码尝试时,我得到了五边形作为内部部分。 - Srinivas
当我使用这段代码时,我发现内部部分是五边形,而按钮则位于圆形的外部。 - Srinivas
我已经更新了我的回答,请您查看问题中的最后一张截图。 - Srinivas
看起来我在button.center和button.transform中使用了错误的值。我修正了center的值,但是button的切片仍然混乱。 - Sarah Zuo
是的,我希望你能检查一下,如果可能的话。我正在尝试使用不同的值,但是我没有得到正确的输出。你能否帮我检查一下? - Srinivas

1

如果所有按钮的图像看起来都像这个(同一个方向),那么变换值可能会生效。

button.transform = CGAffineTransformMakeRotation(2*M_PI-angleSize*j);
button.center = CGPointMake(radius + radius * sin(angleSize * j) / 2, radius +  radius * cos(angleSize * j) / 2);

button slice


虽然这些按钮的宽度和高度相同,但我得到了相同类型的结果。我应该添加那张图片吗?请检查最后2分钟添加的图片。 - Srinivas
@Srinivas,有什么进展吗? - Sarah Zuo

1

您可以使用UIImageView代替。您可以为图像视图添加不同的tag并添加手势识别器。现在,您可以在图像视图上获取触摸事件,就像按钮单击事件一样。


圆形图像是一个UIImageView。 - Srinivas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接