Col*_*ole 2 iphone core-graphics
我有这个代码:
CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, darkColor);
CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
Run Code Online (Sandbox Code Playgroud)
我只是将它放在我视图的viewdidload方法中,但我的视图看起来与之前没有任何不同.我试过让它变得非常大而且明亮的红色,但它只是没画画.我需要一些其他初始化代码吗?
编辑:在给出给我的答案后,我现在在我的veiwdidload中有这个:
[self.view addSubview:[[[imageBackground alloc] init] autorelease]];
Run Code Online (Sandbox Code Playgroud)
并在imageBackground.m中:
@implementation imageBackground
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.opaque = YES;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
darkColor = [[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, darkColor);
CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}
@end
Run Code Online (Sandbox Code Playgroud)
Imagebackground.h子类UIView:
#import <UIKit/UIKit.h>
@interface imageBackground : UIView
@end
Run Code Online (Sandbox Code Playgroud)
尽管如此,我仍然没有得到任何结果.
EDIT2:嗯,我自己解决了,但后来意识到progrmr已经告诉我如何解决它.我不得不使用[self.view addSubview:[[[imageBackground alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease]];而不仅仅是普通的alloc init.
感谢glorifiedhacker提供了很多帮助!
您需要子类化UIView(或其子类之一)并覆盖drawRect方法:
- (void)drawRect:(CGRect)rect {
CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, darkColor);
CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}
Run Code Online (Sandbox Code Playgroud)
为了获得可以绘制的有效图形上下文.来自Apple 关于UIView的文档:
视图绘制根据需要进行.首次显示视图时,或者由于布局更改而使全部或部分视图变为可见时,系统会要求视图绘制其内容.对于包含使用UIKit或Core Graphics的自定义内容的视图,系统会调用视图的drawRect:方法.您对此方法的实现负责将视图的内容绘制到当前图形上下文中,该图形上下文是在调用此方法之前由系统自动设置的.这将创建视图内容的静态可视化表示,然后可以在屏幕上显示.
| 归档时间: |
|
| 查看次数: |
7357 次 |
| 最近记录: |