gpt4 book ai didi

iphone - 为绘图应用程序制作图层结构

转载 作者:行者123 更新时间:2023-12-03 18:03:41 26 4
gpt4 key购买 nike

关于问题an eralier question对于我来说,我尝试创建一个带有 NSMuttableArray 成员变量保存 CALayerRef 的类,但失败了。有人可以指导我如何做到这一点吗?我想做的基本上是创建 CALayerRef 或 CGLayerRef 或其他什么,将它们插入我的 Layers 变量,然后,当我需要时它们,获取,使用它们的上下文,最后绘制/隐藏/显示/删除它们。

我向你们求助,伙计们,因为显然,网上几乎没有关于在高级水平上使用图层和 Quartz 的信息。每个人都可以立即使用这些层,无需管理,无需成员变量。

谢谢。

最佳答案

这是我在几分钟内编写的自定义 View 的一些工作代码,希望对您有所帮助。它创建 10 个绿色层,并每秒将它们动画化到不同的位置。

MBLineLayerDelegate *lineLayerDelegate;
@property (nonatomic, retain) NSMutableArray *ballLayers;

- (void)awakeFromNib
{
self.ballLayers = [NSMutableArray array];
lineLayerDelegate = [[MBLineLayerDelegate alloc] init];
for (NSUInteger i = 0; i < 10; i++) {
CALayer *ball = [CALayer layer];
CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
ball.frame = CGRectMake(x, y, 20, 20);
ball.backgroundColor = [UIColor greenColor].CGColor;
ball.delegate = lineLayerDelegate;
[self.layer addSublayer:ball];
[self.ballLayers addObject:ball];
}

[self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:0];
}

- (void)animateBallsToRandomLocation
{
for (CALayer *layer in self.ballLayers) {
CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
layer.position = CGPointMake(x, y);
}
[self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:1];
}

下面是 CALayer 委托(delegate)绘制一条线的一些代码:

@interface MBLineLayerDelegate : NSObject {
}
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx;
@end

@implementation MBLineLayerDelegate

- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
CGRect rect = layer.bounds;
CGContextSaveGState(context);

CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetAllowsAntialiasing(context, YES);
CGContextSetShouldAntialias(context, YES);

CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, rect.size.width, rect.size.height);

CGContextRestoreGState(context);
}

@end

关于iphone - 为绘图应用程序制作图层结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com