0

我正在使用ImageView渲染圆形渐变来选择颜色。

问题是,只要我panGestureRecognizer留在矩形 ImageView内,即使在圆形渐变之外,他也会继续返回颜色。

有没有办法强制循环边界?

这是将渐变添加到的代码ImageView

CGSize size = CGSizeMake(self.view.bounds.size.width, ((self.view.bounds.size.height)/2));
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), YES, 0.0);
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0,size.width,size.height));


int sectors = 180;
float radius = MIN(size.width, size.height)/2;
float angle = 2 * M_PI/sectors;
UIBezierPath *bezierPath;
for ( int i = 0; i < sectors; i++)
{
    CGPoint center = CGPointMake(((size.width)/2), ((size.height)/2));
    bezierPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:i * angle endAngle:(i + 1) * angle clockwise:YES];
    [bezierPath addLineToPoint:center];
    [bezierPath closePath];
    UIColor *color = [UIColor colorWithHue:((float)i)/sectors saturation:1. brightness:1. alpha:1];
    [color setFill];
    [color setStroke];
    [bezierPath fill];
    [bezierPath stroke];
}
img = UIGraphicsGetImageFromCurrentImageContext();
gradientView = [[UIImageView alloc]initWithImage:img];;
4

1 回答 1

0

你应该检查你的触摸是否在想象的圆圈内。

您所需要的只是非常基本的三角函数。您需要计算触摸点与视图中心之间的距离。如果该距离大于您想要返回而不更改为新颜色的 colorView 的半径(或设置位于 colorView 边缘的值)

我使用这样的东西作为色调和饱和度选择器。

- (void)gestureRecognizerDidPan:(UIPanGestureRecognizer *)gesture {
    CGFloat saturation = 0.0f;
    CGFloat hue = 0.0f;

    UIView *colorView = gesture.view;
    CGPoint location = [gesture locationInView:colorView];

    // we assume that the colored area is a circle inside of a square rect
    CGPoint colorViewCenter = CGPointMake(ceilf(CGRectGetWidth(colorView.bounds)/2.0f), ceilf(CGRectGetHeight(colorView.bounds)/2.0f));
    CGFloat colorViewRadius = floorf(CGRectGetWidth(colorView.bounds)/2.0f);

    CGFloat dx = location.x - colorViewCenter.x;
    CGFloat dy = location.y - colorViewCenter.y;
    CGFloat touchRadius = sqrtf(powf(dx, 2)+powf(dy, 2));
    if (touchRadius > colorViewRadius) {
        // touch was outside of circular area

        // set saturation to max
        saturation = 1.0f;

        // or: 
        // return;
    }
    else {
        saturation = touchRadius / colorViewRadius;
    }

    CGFloat angleRad = atan2f(dx, dy);
    CGFloat angleDeg = (angleRad * (180.0f/M_PI) - 90);
    if (angleDeg < 0.f) {
        angleDeg += 360.f;
    }
    hue = angleDeg / 360.0f;

    // tell your target
}
于 2013-07-15T09:09:46.027 回答