您的位置:首页 > 产品设计 > UI/UE

iOS绘图系列四:绘制文字和图像CGContextDrawImage,drawInRect:,drawAtPoint:, UIGraphicsBeginImageContext

2014-12-03 10:49 176 查看
绘制图形和文字之前需要了解两个坐标系统.

Upper-left-origin coordinate system (ULO) :左上为起始点的坐标系统,UIKit and Core Animation框架用的是这个坐标系统.

Lower-left-origin coordinate system (LLO) :左下为起始点坐标系统,Core
Graphics框架是这个坐标系统.



这两个不同的坐标系统的不同,就必然需要Core Graphics绘制的图片需要上下翻转,才能正常滴在UIView中显示. 此外, UIImage 和 NSString 可以直接绘制,所以不需要像前面绘制圆弧,直线等一样去用UIBezierPath类去绘制了.



实现方法一:通过UIView的drawInRect:方法内用UIKit框架去实现

[[UIImage imageNamed:@"ship"] drawInRect:CGRectMake(10, 30, 80, 80)];
[@"这是一个飞船" drawAtPoint:CGPointMake(10, 120) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]}];


实现方法二:通过UIView的drawInRect:方法内用Core Graphics框架去实现

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
//翻转起来---上下颠倒
CGContextTranslateCTM(ctx, 0.0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

////假设想在10,30,80,80的地方绘制,颠倒过来后的Rect应该是 10, self.bounds.size.height - 110, 80, 80
CGRect imageRect = CGRectMake(10, self.bounds.size.height - 110, 80, 80);
CGContextDrawImage(ctx, imageRect, [UIImage imageNamed:@"Ship"].CGImage);
CGContextRestoreGState(ctx);

//字体在iOS7中被废除了,移入CoreText框架中,以后再详细讨论.
[@"这是一个飞船" drawAtPoint:CGPointMake(10, 120) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]}];
方法三:通过UIGraphicsBeginImageContextWithOptions去方便的创建图片

UIGraphicsBeginImageContext(CGSizeMake(80, 100));

[[UIImage imageNamed:@"ship"] drawInRect:CGRectMake(0, 0, 80, 80)];
[@"这是一个飞船" drawAtPoint:CGPointMake(0, 80) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]}];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


UIGraphicsBeginImageContext(CGSizeMake(80, 100));

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);

//翻转起来---上下颠倒
CGContextTranslateCTM(ctx, 0.0, 100);
CGContextScaleCTM(ctx, 1.0, -1.0);

CGRect imageRect = CGRectMake(0, 20, 80, 80);
CGContextDrawImage(ctx, imageRect, [UIImage imageNamed:@"Ship"].CGImage);
CGContextRestoreGState(ctx);

//字体在iOS7中被废除了,移入CoreText框架中,以后再详细讨论.
[@"这是一个飞船" drawAtPoint:CGPointMake(0, 80) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]}];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: