#import "LinearGradient.h"
@implementation LinearGradient
//線性漸變
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//顏色的分量表示
CGFloat components[] = {1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0};
//顏色的位置
CGFloat locations[] = {1.0, 0.0, 0.5};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 3);
//漸變的區域是當前context,垂直於startPoint <-> endPoint線段,並且於這條線段相交的直線
CGContextDrawLinearGradient(context, gradient, CGPointMake(100, 0), CGPointMake(200, 0), 0);
CGFloat locations2[] = {0.4, 1.0};
CGGradientRef gradient2 = CGGradientCreateWithColorComponents(colorSpace, components, locations2, 2);
//漸變的區域是當前context,垂直於startPoint <-> endPoint線段,並且於這條線段相交的直線
CGContextDrawLinearGradient(context, gradient2, CGPointMake(210, 0), CGPointMake(310, 0), 0);
}
@end
#import "RadialGradientView.h"
@implementation RadialGradientView
//環狀漸變
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSArray *array = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor blueColor].CGColor, (__bridge id)[UIColor purpleColor].CGColor];
CGFloat locations[] = {0.0, 0.5, 1.0};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)array, locations);
CGContextDrawRadialGradient(context, gradient, CGPointMake(200, 200), 0, CGPointMake(150, 200), 100, 0);
}
@end
//將繪制圖片保存
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 100, 100));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
NSData *data = UIImageJPEGRepresentation(image, 1.0);
// NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:@"/Users/apple/desktop/image.jpg" atomically:YES];
UIGraphicsEndImageContext();
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end