[英]Overriding drawRect:(CGRect)rect in Objective-C (iOS)?
I was overriding the drawRect:(CGRect)rect
method while making a simple iOS application. 在制作一个简单的iOS应用程序时,我重写了
drawRect:(CGRect)rect
方法。 In the book I was reading, the bounds were defined using self.bounds
as shown here: 在我正在阅读的书中,界限是使用
self.bounds
定义的,如下所示:
- (void)drawRect:(CGRect)rect
{
CGRect bounds = self.bounds;
//rest of drawing code here
}
I noticed that in the book, the rest of the method did not even use the rect
argument and worked fine. 我注意到在书中,该方法的其余部分甚至都没有使用
rect
参数并且可以正常工作。 I assumed that rect
would set the bounds in the view, so I tried the following: 我认为
rect
将在视图中设置边界,因此我尝试了以下操作:
- (void)drawRect:(CGRect)rect
{
CGRect bounds = rect;
//rest of drawing code here
}
(Obviously, I would not even need to make bounds
equal to rect
since I can refer directly to rect
within the method.) I tried both ways and they yielded the same result. (显然,我不会需要做
bounds
等于rect
,因为我可以直接引用rect
的方法中)。我试过两种方式与他们取得了同样的结果。 So are self.bounds
and rect
equal? 那么
self.bounds
和rect
相等吗? If they are, I am assuming rect
is used to set the bounds of the current view somewhere behind the scenes. 如果是这样,我假设使用
rect
来将当前视图的边界设置在幕后某处。 But if they are not, what is the use of having rect
as an argument to a method that does not even use it? 但是,如果不是,那么将
rect
用作甚至不使用它的方法的参数有什么用? Am I overlooking something obvious? 我是否忽略了明显的东西?
rect
tells you which area you need to draw . rect
告诉您您需要绘制哪个区域。 It will always be less than or equal to self.bounds
. 它将始终小于或等于
self.bounds
。 As per the documentation (emphasis added): 根据文档 (添加重点):
The portion of the view's bounds that needs to be updated.
视图边界中需要更新的部分。 The first time your view is drawn, this rectangle is typically the entire visible bounds of your view.
第一次绘制视图时,此矩形通常是视图的整个可见范围。 However, during subsequent drawing operations, the rectangle may specify only part of your view.
但是,在后续的绘图操作中,矩形可能仅指定视图的一部分。
If it's less efficient for you to draw subdivisions of your view then you might as well draw the whole thing. 如果绘制视图的细分对您来说效率较低,那么您最好绘制整个视图。
In practice just drawing the whole thing is pretty much never a bottleneck so most people just do that as per the rule that the simplest code is preferable unless or until performance requires a different approach. 在实践中,仅绘制整个内容几乎绝不是瓶颈,因此大多数人只是按照这样的规则进行操作:最简单的代码是可取的,除非或直到性能需要其他方法为止。
drawRect is written to pass in a rectangle that the method is supposed to draw. 将drawRect编写为传递该方法应该绘制的矩形。 It's possible that the system may decide that only a portion of the view (perhaps because most of the view is covered by another view.
系统可能会决定仅视图的一部分(也许是因为大多数视图被另一个视图覆盖了)。
If only a portion of the view needs to be drawn, it can be faster to only draw that part. 如果只需要绘制视图的一部分,则仅绘制该部分会更快。
As Tommy said while I was typing my answer, it is sometimes easier to just draw the entire view. 正如汤米在输入答案时所说的那样,有时候绘制整个视图有时会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.