繪制原理
當一個應用程序繪制圖像時奶镶,它首先會創(chuàng)建一個畫布以供繪制沪停。Cocoa把它稱為圖像的上下文笔横。上下文定義了畫布的大小和顏色信息的使用方式(例如,你可以有一個黑白畫布沦偎,一個灰度畫布等)疫向。
一旦創(chuàng)建好上下文,就可以請求Cocoa開始繪制內(nèi)容扛施。
繪圖的基本單元是路徑鸿捧。一個路徑只是任意形狀的名字。
構(gòu)建路徑時疙渣,需要指定路徑的關鍵點匙奴。
在iOS上繪制陰影:
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef shadow = [UIColor redColor].CGColor;
CGSize shadowOffset = CGSizeMake(3, 3);
CGFloat shadowBlurRadius = 5;
CGRect pathRect = CGRectInset(self.bounds, 20, 20);
UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRect:pathRect];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow);
[[UIColor lightGrayColor] setFill];
[rectanglePath fill];
CGContextRestoreGState(context);
在iOS上繪制漸變
剪切當前圖形上下文,然后從屏幕一個點到另一個點繪制漸變妄荔。
傳遞視圖坐標空間中漸變開始和結(jié)束的坐標泼菌。
// 繪制漸變
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *gradientStartColor = [UIColor colorWithRed:0.0
green:0.2
blue:0.7
alpha:1];
UIColor *gradientEndColor = [UIColor colorWithRed:0.3
green:0.4
blue:0.7
alpha:1];
NSArray *gradientColors = @[(id)gradientStartColor.CGColor, (id)gradientEndColor.CGColor];
CGFloat gradientLocations[] = {0, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations);
CGRect pathRect = CGRectInset(self.bounds, 20, 20);
CGPoint topPoint = CGPointMake(self.bounds.size.width / 2, 20);
CGPoint bottomPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 20);
UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:4];
CGContextSaveGState(context);
[roundedRectanglePath addClip];
CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);