gpt4 book ai didi

ios - 在 UIImageView 的圆形图像中选择一个随机点

转载 作者:行者123 更新时间:2023-11-28 18:29:08 25 4
gpt4 key购买 nike

我有一个带有色轮的应用程序,我试图在色轮中随机选择一种颜色。但是,我在验证随机点是否落在色轮内时遇到问题。

这是目前的代码:

CGPoint randomPoint = CGPointMake(arc4random() % (int)colorWheel.bounds.size.width, arc4random() % (int)colorWheel.bounds.size.height);
UIColor *randomColor = [self colorOfPoint:randomPoint];

CGPoint pointInView = [colorWheel convertPoint:randomPoint fromView:colorWheel.window];
if (CGRectContainsPoint(colorWheel.bounds, pointInView)) {
NSLog(@"%@", randomColor);
}
else {
NSLog(@"out of bounds");
}

验证我尝试过但没有成功的观点的其他几种方法:

if (CGRectContainsPoint(colorWheel.frame, randomPoint)) {
NSLog(@"%@", randomColor);
}

if ([colorWheel pointInside:[self.view convertPoint:randomPoint toView: colorWheel] withEvent: nil]) {
NSLog(@"%@", randomColor);
}

有时会输出“out of bounds”,有时只会输出颜色为白色(色轮周围的背景当前为白色,但色轮图像中没有白色)。

色轮图像是一个圆圈,所以我不确定这是否会影响测试,尽管白色似乎过于频繁地弹出,以至于它只是图像周围的透明方形轮廓,呈现出白色.

最佳答案

如果你想生成一个圆上的随机点,你最好在极坐标中选择你的点,然后将其转换为笛卡尔坐标。

极坐标空间使用两个维度,半径角度。半径就是距中心的距离,角度通常从“正东”开始为 0,然后逆时针旋转直到 2π(以弧度为单位,360˚ 当然以度为单位)。

大概你的轮子被分成简单的楔子,所以半径实际上并不重要;你只需要选择一个随机角度。

uint32_t angle = arc4random_uniform(360);
// Radius will just be halfway from the center to the edge.
// This assumes the circle is exactly enclosed, i.e., diameter == width
CGFloat radius = colorWheel.bounds.size.width / 4;

此函数将为您提供极坐标中的笛卡尔点。 Wikipedia explains the simple math如果你有兴趣。

/** Convert the polar point (radius, theta) to a Cartesian (x,y). */
CGPoint poltocar(CGFloat radius, CGFloat theta)
{
return (CGPoint){radius * cos(theta), radius * sin(theta)};
}

该函数对theta使用弧度,因为sin()cos()都是这样,所以把角度换成弧度,然后你可以转换:

CGFloat theta = (angle * M_PI) / 180.0
CGPoint randomPoint = poltocar(radius, theta);

最后一步:这个圆的原点和 View 在同一个地方,也就是在角落里,所以你需要平移这个点,以圆心为原点。

CGPoint addPoints(CGPoint lhs, CGPoint rhs)
{
return (CGPoint){lhs.x + rhs.x, lhs.y, rhs.y};
}

CGPoint offset = (CGPoint){colorWheel.bounds.size.width / 2,
colorWheel.bounds.size.height / 2};

randomPoint = addPoints(randomPoint, offset);

而你的新 randomPoint 将始终在圆圈内。

关于ios - 在 UIImageView 的圆形图像中选择一个随机点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com