iOS坐标系的深入探究

2020-01-21 07:39:04王振洲

前言

app在渲染视图时,需要在坐标系中指定绘制区域。

这个概念看似乎简单,事实并非如此。

When an app draws something in iOS, it has to locate the drawn content in a two-dimensional space defined by a coordinate system.
This notion might seem straightforward at first glance, but it isn't.

正文

我们先从一段最简单的代码入手,在drawRect中显示一个普通的UILabel;

为了方便判断,我把整个view的背景设置成黑色:


- (void)drawRect:(CGRect)rect {
 [super drawRect:rect];
 CGContextRef context = UIGraphicsGetCurrentContext();
 NSLog(@"CGContext default CTM matrix %@", NSStringFromCGAffineTransform(CGContextGetCTM(context)));
 UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 28)];
 testLabel.text = @"测试文本";
 testLabel.font = [UIFont systemFontOfSize:14];
 testLabel.textColor = [UIColor whiteColor];
 [testLabel.layer renderInContext:context];
}

这段代码首先创建一个UILabel,然后设置文本,显示到屏幕上,没有修改坐标。

所以按照UILabel.layer