美文网首页
【Objective-C笔记】—— 视图和Core Graphi

【Objective-C笔记】—— 视图和Core Graphi

作者: u14e | 来源:发表于2017-06-18 07:38 被阅读35次

bounds和frame

bounds表示的矩形位于自己的坐标系,frame表示的矩形位于父视图的坐标系,但是两个矩形的大小是相同的。(bounds.origin.xbounds.origin.y始终未0)
frame用于确定与视图层次结构中其他视图的相对位置,从而将自己的图层与其他视图的图层正确组合成屏幕的图像
bounds用于确定绘制区域,避免将自己绘制到图层边界之外

Core Graphics

Core Graphics是一套提供2D绘图功能的C语言API。使用C语言的结构和函数模拟了一套面向对象的编程机制
Core Graphics中最重要的对象是图形上下文(graphics context),图形上下文是CGContextRef结构的对象,负责存储绘画状态(如画笔颜色、线条粗细)和绘制内容所在的内存空间

视图的drawRect:方法在执行之前,系统首先为视图的图层创建一个图形上下文,然后为绘画状态设置一些默认参数。drawRect:方法开始执行时,随着图形上下文不断执行绘图操作,图层上的内容随之改变。drawRect:执行完毕后,系统将图层与其他图层一起组合成完整的图像并显示在屏幕上

objective-c实现

[[UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:1.0] setStroke];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:a];
[path addLineToPoint:b];
[path stroke];

Core Graphics实现

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSetRGBStrokeColor(currentContext, 1, 0, 0, 1);

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(currentContext, NULL, a.x, a.y);
CGPathAddLineToPoint(currentContext, NULL, b.x, b.y);
CGContextAddPath(currentContext, path);

CGContextStrokePath(currentContext);
CGPathRelease(path);

带Ref后缀的C结构是用来模拟面向对象机制的,算是一个“对象”,创建“对象”时,也是返回一个指向对象内存地址的指针

使用Core Graphics绘制阴影和渐变

绘制阴影之前,需要将阴影效果添加到一个图形上下文中,之后再改图形上下文中绘制的所有不透明图像都会带有阴影效果

注意没有删除阴影效果的函数,所以需要在添加阴影效果之前保存绘图状态,之后再回复没有阴影效果的状态

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSaveGState(currentContext);         // 保存绘图状态
CGContextSetShadow(currentContext, CGSizeMake(4, 7), 3);
// 在这里绘制的图像会带有阴影效果
// 绘制图像
UIImage *logoImage = [UIImage imageNamed:@"logo"];
[logoImage drawInRect: rect];

CGContextRestoreGState(currentContext);    // 恢复之前的绘图状态
// 在这里绘制的图像不带阴影效果

渐变

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSaveGState(currentContext);         // 保存绘图状态

CGFloat locations[2] = {0.0, 1.0};
CGFloat components[8] = {1, 0, 0, 1,     // 起始颜色red
                         1, 1, 0, 1};       // 终止颜色yellow
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, 2);

CGPoint startPoint = CGPointMake(0, 0);
CGPoint endPoint = CGPointMake(0, 30);
CGContextDrawLinearGradient(currentContext, gradient, startPoint, endPoint, 0);

CGGradientRelease(gradient);
CGColorSpaceRelease(colorspace);

CGContextRestoreGState(currentContext);    // 恢复之前的绘图状态

CGContextDrawLinearGradient最后一个参数用来设置起始位置和终止位置以外的绘制区域的颜色填充方式。

  • kCGGradientDrawsBeforeStartLocation使用起始颜色填充起始位置之前的绘制区域
  • kCGGradientDrawsAfterEndLocation使用终止颜色填充终止位置之后的绘制区域
  • kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation起始和终止都要填充
  • 0都不填充

相关文章

网友评论

      本文标题:【Objective-C笔记】—— 视图和Core Graphi

      本文链接:https://www.haomeiwen.com/subject/kcciqxtx.html