ios 图像坐标系_iOS坐标系探究

本文深入探讨了iOS中的坐标系,包括UILabel的绘制、CoreText渲染文字时的坐标问题。通过示例代码,解释了坐标变换如何影响图形绘制,特别是CoreGraphics坐标系与UIKit坐标系之间的转换。最后,文章解决了CoreText渲染文字上下颠倒的问题,并讨论了在不同坐标系中如何兼容UILabel和CoreText的绘制。
摘要由CSDN通过智能技术生成

前言

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默认的坐标(0, 0),在左上角进行了绘制。

UILabel绘制

接着,我们尝试使用CoreText来渲染一段文本。

- (void)drawRect:(CGRect)rect {

[super drawRect:rect];

CGContextRef context = UIGraphicsGetCurrentContext();

NSLog(@"CGContext default matrix %@", NSStringFromCGAffineTransform(CGContextGetCTM(context)));

NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"测试文本" attributes:@{

NSForegroundColorAttributeName:[UIColor whiteColor],

NSFontAttributeName:[UIFont systemFontOfSize:14],

}];

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值