gpt4 book ai didi

ios - 如何在持久 Canvas 上绘图并将其绘制在 View 内?

转载 作者:行者123 更新时间:2023-11-29 05:03:43 27 4
gpt4 key购买 nike

我正在为 iOS 编写一个小型绘画应用程序。我正在对 UIView 广告进行子类化,在其 drawRect: 方法内执行计算。一切都很好,直到我开始拥有大量对象(实际上是折线),然后性能开始下降。

- (void)drawRect:(CGRect)rect {
[super drawRect:rect];

CGContextRef imageContext = UIGraphicsGetCurrentContext();

int i, j;
for(i = 0; i < [_strokes count]; i++) {
NSMutableArray *stroke = [_strokes objectAtIndex:i];
if([stroke count] < 2) {
continue;
}
CGContextSetStrokeColorWithColor(imageContext, [[_penColours objectAtIndex:i] CGColor]);
for(j = 0; j < [stroke count]-1; j++) {
CGPoint line[] = {
[[stroke objectAtIndex:j] CGPointValue],
[[stroke objectAtIndex:j+1] CGPointValue]
};

CGContextSetLineWidth(imageContext, _brushSize);
CGContextSetLineCap(imageContext, kCGLineCapRound);
CGContextSetLineJoin(imageContext, kCGLineJoinRound);

CGContextAddLines(imageContext, line, 2);
CGContextStrokePath(imageContext);
}
}

CGContextFlush(imageContext);
}

其中 _lines 是点数组的数组。我的第一个想法是将图像制作为 ivar,将其绘制在上下文上,将附加笔画绘制到上下文(将 j = 0 更改为 j = [Stroke count] - 2),并获取图像的上下文并将其存储回 ivar。没有成功。

然后我尝试了许多其他并不值得一提的道路,直到我在 SO ( Quartz2D performance - how to improve ) 上发现了另一个问题。不幸的是,它没有像我预期的那样工作,因为我必须保留图像,导致内存警告 1、2、崩溃。

- (void)drawRect:(CGRect)rect {
[super drawRect:rect];

UIGraphicsBeginImageContext(CGSizeMake(1024, 768));
CGContextRef imageContext = UIGraphicsGetCurrentContext();

if(_image != nil) {
CGContextDrawImage(imageContext, CGRectMake(0, 0, 1024, 768), [_image CGImage]);
}

int i, j;
for(i = 0; i < [_strokes count]; i++) {
NSMutableArray *stroke = [_strokes objectAtIndex:i];
if([stroke count] < 2) {
continue;
}
CGContextSetStrokeColorWithColor(imageContext, [[_penColours objectAtIndex:i] CGColor]);
for(j = [stroke count]-2; j < [stroke count]-1; j++) {
CGPoint line[] = {
[[stroke objectAtIndex:j] CGPointValue],
[[stroke objectAtIndex:j+1] CGPointValue]
};

CGContextSetLineWidth(imageContext, _brushSize);
CGContextSetLineCap(imageContext, kCGLineCapRound);
CGContextSetLineJoin(imageContext, kCGLineJoinRound);

CGContextAddLines(imageContext, line, 2);
CGContextStrokePath(imageContext);
}
}

_image = UIGraphicsGetImageFromCurrentImageContext();
[_image retain];
UIGraphicsEndImageContext();

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, CGRectMake(0, 0, 1024, 768), [_image CGImage]);
}

最佳答案

看起来至少部分问题是您保留了 _image 但从未释放它。每次为 _image 分配新值时,都会泄漏前一个图像,这会很快填满内存。

除此之外,您可能应该使用 CGLayer用于屏幕外绘图而不是位图。您可以随时在图层中绘制内容,然后只需在 -drawRect: 方法中将其复制到屏幕即可。

关于ios - 如何在持久 Canvas 上绘图并将其绘制在 View 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198375/

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