《iOS 编程》4. 视图层次结构

独立做练习的过程中学习和收获的很多,很多原本认为了解的知识变成了理解和会用的知识。官方文档还有待熟悉。

frame vs bounds

4.2 视图层次结构

View

4.6 初级练习:绘制图片

GWHypnosisView.m- (void)drawRect:(CGRect)rect{}添加以下代码:

1
2
3
4
5
6
7
// 添加logo,中心点为屏幕中心点
CGRect logoFrame = CGRectMake(center.x - bounds.size.width / 4, center.y - bounds.size.height / 4, bounds.size.width / 4 * 2, bounds.size.height / 4 * 2);
UIImage *logoimage = [UIImage imageNamed:@"logo.png"];
[logoimage drawInRect:logoFrame];
UIView *logoView = [[UIView alloc]initWithFrame:logoFrame];
[self.window addSubview:logoView];

4.8 高级练习:阴影和渐变

GWHypnosisView.m- (void)drawRect:(CGRect)rect{}添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

// 添加三角形,并添加渐变效果

CGContextRef triangleContext = UIGraphicsGetCurrentContext();

UIBezierPath *trianglePath = [[UIBezierPath alloc] init];
[trianglePath moveToPoint:CGPointMake(center.x + bounds.size.width / 3, center.y + bounds.size.height / 3)];
[trianglePath addLineToPoint:CGPointMake(center.x - bounds.size.width / 3, center.y + bounds.size.height / 3)];
[trianglePath addLineToPoint:CGPointMake(center.x, center.y - bounds.size.height / 3)];
[trianglePath addLineToPoint:CGPointMake(center.x + bounds.size.width / 3, center.y + bounds.size.height / 3)];
[trianglePath stroke];

CGContextSaveGState(triangleContext);
[trianglePath addClip];


CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 0.0, 1.0,
0.0, 0.5, 0.0, 1.0 };
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, 2);

CGPoint startPoint = CGPointMake(center.x, center.y + bounds.size.height / 3 );
CGPoint endPoint = CGPointMake(center.x, center.y - bounds.size.height / 3 );
CGContextDrawLinearGradient(triangleContext, gradient, startPoint, endPoint, 0);

CGGradientRelease(gradient);
CGColorSpaceRelease(colorspace);

CGContextRestoreGState(triangleContext);

// 添加阴影
CGContextRef logoContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(logoContext);
CGContextSetShadow(logoContext, CGSizeMake(4, 7), 3);


// 添加logo,中心点为屏幕中心点
CGRect logoFrame = CGRectMake(center.x - bounds.size.width / 4, center.y - bounds.size.height / 4, bounds.size.width / 4 * 2, bounds.size.height / 4 * 2);
UIImage *logoimage = [UIImage imageNamed:@"logo.png"];
[logoimage drawInRect:logoFrame];
UIView *logoView = [[UIView alloc]initWithFrame:logoFrame];
[self.window addSubview:logoView];

CGContextRestoreGState(logoContext);


最终效果图:

Hypnosister

项目代码保存在我的 GitHub: iOSProgramming4edSolutions