CoreGraphics グラデーション

CoreGraphicsを使って, グラデーションを描画します。

グラーデーションに必要なものといえば, 色パターン, 色の位置, 方向です。

描画のステップはこんな感じです。

1. カラー配列を作成
[r, g, b, a, r, g, b, a, ….], 0.0〜1.0までの数字の配列をrgbaの順番で作ります。

2. 色の位置の座標配列を作ります
例)

CGFloat shineGradientLocations[] = {0, 0.42, 1};

0〜1.0までどのあたりで次の色に変更するかの相対位置を入れます。色の数だけ必要です

3. CGColorSpaceRefの用意

CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

4. CGGradientRefの用意

5. 描画領域をクリップする

6. 2点を指定してグラディエーションを行う

サンプル

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGFloat colors[] = {
        1.0, 0.0, 0.0, 1.0,
        1.0, 1.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0 };
    CGFloat locs[] = {0.0, 0.5, 1.0};
    CGColorSpaceRef space =
    CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(space,colors, locs, 3);
    
    CGRect r1 = CGRectMake(20.0 , 20.0, 100.0, 100.0);
    CGContextClipToRect(context, r1);
    CGPoint p1 = CGPointMake(20.0, 20.0);
    CGPoint p2 = CGPointMake(120.0, 120.0);
    
    CGContextDrawLinearGradient(context, gradient, p1, p2, 0);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(space);
}

coregraphics-gradient

これは直線Gradientの例です。ほかにも円グラデーションなんかもあります。

CGContextDrawRadialGradient( CGContextRef, 
CGGradientRef, 開始位置, 半径, 終了位置, 半径, オプション );

サンプル2

SmokeView.m

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat colors[] = {1.0f, 1.0f, 1.0f, 1.0f,
                        1.0f, 1.0f, 1.0f, 0.5f,
                        1.0f, 1.0f, 1.0f, 0.0f};
    
    CGFloat locs[] = {0.0, 0.8f, 1.0f};
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(space, colors, locs, 3);
    
    CGContextClipToRect(context, rect);
    CGPoint start = CGPointMake(rect.size.width, 0);
    CGPoint end = CGPointMake(0, 0);
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsAfterEndLocation);
    CGColorSpaceRelease(space);
}

How to use

@interface SmokeViewController ()
@property (nonatomic)SmokeView *smokeView;
@end

@implementation SmokeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];    
    self.smokeView = [[SmokeView alloc] init];
    [self.view setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:self.smokeView];
}

- (void)viewWillLayoutSubviews {
    self.smokeView.frame = CGRectMake(100, 100, 100, 100);
}
@end

左から右へグラデーションしたものです
SmokeView