0

코어 그래픽을 사용하여 검은 색과 흰색색의 방사형 그래디언트를 만드는 것이 매우 간단해야하지만 많은 시도 후에도 내가 잘못되고있는 부분을 파악할 수 없습니다.검은 색과 흰색의 방사형 그래디언트 그라데이션이 전체 검은 색 화면을 표시합니다.

CGFloat radius = shapeRect.size.width/2.0; 
CGPoint center = CGPointMake(shapeRect.origin.x+shapeRect.size.width/2, shapeRect.origin.y+shapeRect.size.height/2); 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 
CGContextRef context = CGBitmapContextCreate(NULL, shapeRect.size.width, shapeRect.size.height, 8, shapeRect.size.width*4, colorSpace, kCGImageAlphaNone); 
CGFloat components[] = {0.0, 1.0}; 
CGFloat locations[] = {0.0, 1.0}; 
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2); 
CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, 0); 

CGImageRef img = CGBitmapContextCreateImage(context); 
[maskedView setImage:[UIImage imageWithCGImage:img]]; 

CGGradientRelease(gradient); 
CGContextRelease(context); 
CGColorSpaceRelease(colorSpace); 

여기 ShapeRect self.view 경계가 있습니다 enter image description here

이 내 코드입니다 :

나는 이런 식으로 뭔가를 할 수 있습니다.

출력으로 그라데이션이없는 검은 색 화면이 나타납니다. iPhone 7 시뮬레이터를 사용하고 있습니다.

제안 사항은 저축 할 수 있습니다.

감사합니다.

답변

0

이 스 니펫을 확인하십시오. componentslocations 값을 변경하여 원하는 것을 얻고 드로잉이 어떻게 작동하는지 이해할 수 있습니다. CGGradientCreateWithColorComponentsdescription

#import "TestView.h" 

@implementation TestView { 
    CGGradientRef _gradient; 
} 

-(void)drawRect:(CGRect)rect 
{ 
    CGFloat radius = self.frame.size.width/2.0; 
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGGradientRef gradient = [self createGradient]; 
    CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, kCGGradientDrawsBeforeStartLocation); 
} 

-(CGGradientRef)createGradient 
{ 
    if (!_gradient) { 
     CGFloat components[] = { 0.0, 1.0, 0.5, 0.5, 1.0, 0.3 }; 
     CGFloat locations[] = { 0.0, 0.6, 1.0 }; 
     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 
     _gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 3); 
     CGColorSpaceRelease(colorSpace); 
    } 
    return _gradient; 
} 

- (void)layoutSubviews 
{ 
    self.backgroundColor = [UIColor whiteColor]; 
    self.layer.borderColor = [UIColor lightGrayColor].CGColor; 
    self.layer.borderWidth = 1.; 
} 


@end 

결과를 참조하십시오

enter image description here

관련 문제