2011-02-07 7 views
7

그래디언트 - 채우기 또는 획으로 그리는 방법과 관련하여 웹 및 여기에 다양한 리소스가 있습니다.코어 그래픽 : 일반 그래디언트가있는 패스 그리기

그러나 AFAICT는 없음 다음 요구 사항을 해결 아니오 정상 경로에 직교하는 수단, 이에 정상 구배로 경로를 그리는 방법. 그물 효과는 어두운 → 밝은 → 어두운 선형 그라디언트로 적용 할 때 치약이나 튜브와 같은 것일 수 있습니다.

round-rect tube http://muys.net/cadre_blanc.png

(이 손으로 그린이고 모서리가 아주 좋지 않다) : 여기에 둥근 직사각형의 경우이 좋습니다.

둥근 rect의 특별한 경우에는 4 개의 선형 그라디언트 (측면)와 4 개의 방사형 그라디언트 (모서리)로이 효과를 얻을 수 있다고 생각합니다. 그러나 더 나아 졌습니까?

경로에 대한 쉬운 해결책이 있습니까?

답변

6

그라디언트를 시뮬레이트하기 위해 필자가 생각할 수있는 유일한 "쉬운"해결책은 패스를 여러 번 선 획하고 획 폭을 줄이며 매번 약간의 색상을 변경하는 것입니다.

분명히 복잡한 경로에서는 값 비싼 연산이므로 가능한 경우 결과를 캐시해야합니다.

#define RKRandom(x) (arc4random() % ((NSUInteger)(x) + 1)) 

@implementation StrokeView 

- (void)drawRect:(NSRect)rect 
{ 
    NSRect bounds = self.bounds; 

    //first draw using Core Graphics calls 
    CGContextRef c = [[NSGraphicsContext currentContext] graphicsPort]; 

    CGMutablePathRef path = CGPathCreateMutable(); 

    CGPathMoveToPoint(path, NULL, NSMidX(bounds), NSMidY(bounds)); 
    CGContextSetMiterLimit(c,90.0); 
    CGContextSetLineJoin(c, kCGLineJoinRound); 
    CGContextSetLineCap(c, kCGLineCapRound); 

    for(NSUInteger f = 0; f < 20; f++) 
    { 
     CGPathAddCurveToPoint(
           path, 
           NULL, 
           (CGFloat)RKRandom((NSInteger)NSWidth(bounds)) + NSMinX(bounds), 
           (CGFloat)RKRandom((NSInteger)NSHeight(bounds)) + NSMinY(bounds), 
           (CGFloat)RKRandom((NSInteger)NSWidth(bounds)) + NSMinX(bounds), 
           (CGFloat)RKRandom((NSInteger)NSHeight(bounds)) + NSMinY(bounds), 
           (CGFloat)RKRandom((NSInteger)NSWidth(bounds)) + NSMinX(bounds), 
           (CGFloat)RKRandom((NSInteger)NSHeight(bounds)) + NSMinY(bounds) 
          ); 
    } 

    for(NSInteger i = 0; i < 8; i+=2) 
    { 
     CGContextSetLineWidth(c, 8.0 - (CGFloat)i); 
     CGFloat tint = (CGFloat)i * 0.15; 

     CGContextSetRGBStrokeColor (
            c, 
            1.0, 
            tint, 
            tint, 
            1.0 
            ); 
     CGContextAddPath(c, path); 
     CGContextStrokePath(c); 
    } 

    CGPathRelease(path); 

    //now draw using Cocoa drawing 
    NSBezierPath* cocoaPath = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds, 20.0, 20.0) xRadius:10.0 yRadius:10.0]; 
    for(NSInteger i = 0; i < 8; i+=2) 
    { 
     [cocoaPath setLineWidth:8.0 - (CGFloat)i]; 
     CGFloat tint = (CGFloat)i * 0.15; 
     NSColor* color = [NSColor colorWithCalibratedRed:tint green:tint blue:1.0 alpha:1.0]; 
     [color set]; 
     [cocoaPath stroke]; 
    } 
} 

@end 

sample output

관련 문제