我正在尝试学习 Core Animation 来开发某个应用程序,但我需要继承 CALayer 类,但是我正在努力让图层自行绘制。
我需要自定义 CALayer 来拥有一些额外的属性并处理自定义事件(触摸等),但是从一开始我正在实现的基本 CALayer 并没有绘制它自己,谁能告诉我我做错了什么?
我有一个 魔方
#import "MagicSquare.h"
@implementation MagicSquare
-(id) initWithLayer:(id)layer {
self = [super initWithLayer:layer];
self.bounds = CGRectMake(0, 0, 200, 200);
self.position = CGPointMake(10,10);
self.cornerRadius = 100;
self.borderColor = [UIColor redColor].CGColor;
self.borderWidth = 1.5;
return self;
}
- (void)drawInContext:(CGContextRef)theContext
{
NSLog(@"Drawing");
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath,NULL,15.0f,15.f);
CGPathAddCurveToPoint(thePath,
NULL,
15.f,250.0f,
295.0f,250.0f,
295.0f,15.0f);
CGContextBeginPath(theContext);
CGContextAddPath(theContext, thePath );
CGContextSetLineWidth(theContext,
1.0);
CGContextSetStrokeColorWithColor(theContext,
[UIColor redColor].CGColor);
CGContextStrokePath(theContext);
CFRelease(thePath);
}
下面是我试图让它在主 Controller 上绘制的方法
@implementation BIDViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MagicSquare *layer = [[MagicSquare alloc] initWithLayer:[CALayer layer]];
[self.view.layer addSublayer:layer];
}
最佳答案
找到问题了。
我需要在图层上调用 setNeedsDisplay,因为它不会自动绘制:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MagicSquare *layer = [[MagicSquare alloc] initWithLayer:[CALayer layer]];
[self.view.layer addSublayer:layer];
[layer setNeedsDisplay];
}
关于ios - 创建自定义 CALayer 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12232168/