绘制矩形的问题 [英] Problem in draw rect
问题描述
我在viewLoad中使用下面的代码(我不想在 - (void)drawRect:(CGRect)rect
中绘制)在视图上添加rect而不是' t work.why?
I use below code in viewLoad (i don't want to draw in - (void)drawRect:(CGRect)rect
)for add rect on view but doesn't work.why?
CGRect rect=CGRectMake(10,10,150,140);
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(context, red);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 10, 10);
CGContextAddRect(context, rect);
CGContextStrokePath(context);
推荐答案
UIGraphicsGetCurrentContext()当没有当前上下文时,code>将返回nil。在调用
drawRect:
之前为您创建一个上下文;如果要手动创建上下文,请使用 UIGraphicsBeginImageContext
或 UIGraphicsBeginImageContextWithOptions
启动上下文, UIGraphicsGetImageFromCurrentImageContext ()
提取UIImage,以及 UIGraphicsEndImageContext()
,当你完成它以释放上下文时。有关详细信息,请参见文档。
UIGraphicsGetCurrentContext()
will return nil when there is no current context. A context is created for you before drawRect:
is called; if you want to create a context manually, use UIGraphicsBeginImageContext
or UIGraphicsBeginImageContextWithOptions
to start one, UIGraphicsGetImageFromCurrentImageContext()
to extract the UIImage, and UIGraphicsEndImageContext()
when you're done with it to release the context. See the documentation for details.
当然,你也可以创建一个 CGBitmapContextRef 并直接使用CoreGraphics调用而不是UIKit调用。每种方法都有优缺点,主要区别在于默认转换矩阵。
You could also, of course, create a CGBitmapContextRef and use CoreGraphics calls directly rather than UIKit calls. There are pros and cons to each approach, the major difference being the default transformation matrix.
这篇关于绘制矩形的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!