2013-07-15 51 views
0

我正在使用ImageView來呈現選擇顏色的圓形漸變。給出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];; 
+0

檢查鍋的位置。如果它在想象圓的外面,則不返回顏色。 –

+0

以及如何做到這一點? – Exothug

回答

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 
}