ios - 创建自定义 CALayer 实现

标签 ios core-animation

我正在尝试学习 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/

相关文章:

iPhone 动画问题 SIMulator 与 Real Device

ios - 对 UICollectionView 中的特定单元格进行动画处理

xcode - 在 OS X Cocoa 中将 NSButton 添加到 CALayer

ios - 处理 Collection View Cell 中元素的手势事件

iOS - 简单的 Facebook 身份验证

ios - 删除列表框中包含组标题的项目

ios - 如何获取我的蓝牙设备服务 UUID? swift

ios - 是否可以在 Xcode 7 中编译 Swift 2 代码并在 iOS 11.1 iPhone 6 上运行它?

iphone - 图层动画第一次工作正常,但在第二次相同调用时就不行

iphone - CAAnimation 的问题