gpt4 book ai didi

ios - drawRect中的for循环

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

我需要在 View Controller 中绘制图表。我已经创建了一个 ScrollView 和一个 View 作为我的 self.view 的 subview ,具有自动布局。我的数据来自一个包含数千个 NSNumber 的数组(核心数据)。现在,这是我使用的代码:

//viewController.m
@implementation viewController{
NSArray *array;
UIScrollView *scrollView;
graphView *embedGraphView; //graphView is a subclass of UIView
}

- (void)viewDidLoad{
array = @[...]; //thousand of NSNumber from Core Data Model

//Auto layout
scrollView = [[UIScrollView alloc] init];
scrollView.delegate = self;
scrollView.alwaysBounceHorizontal = YES;
[self.view addSubview:scrollView];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;

embedGraphView = [[graphView alloc] init];
[embedGraphView setBackgroundColor:[UIColor whiteColor]];
embedGraphView.array = array;
embedGraphView.maxValue = [[array valueForKeyPath:@"@max.doubleValue"]doubleValue];
[scrollView addSubview:embedGraphView];
embedGraphView.translatesAutoresizingMaskIntoConstraints = NO;

NSDictionary *metrics = @{@"width":@(array.count)};
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(scrollView, embedGraphView);

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics:0 views:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[embedGraphView(width)]|" options:0 metrics:metrics views:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[embedGraphView(scrollView)]|" options:0 metrics:0 views:viewsDictionary]];
}

//graphView.h
@interface graphView : UIView
@property (strong, nonatomic) NSArray *array;
@property double maxValue;

//graphView.m
@implementation graphView
- (void)drawRect:(CGRect)rect{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 0.5);
CGContextSetStrokeColorWithColor(ctx, [[UIColor blueColor] CGColor]);
CGContextMoveToPoint(ctx, 0, self.frame.size.height - [self.array[0]doubleValue] / self.maxValue * (self.frame.size.height-10));

if ((float)self.array.count == self.frame.size.width){
for (NSInteger i = 1; i < self.array.count; i++)
{
CGContextAddLineToPoint(ctx, i, self.frame.size.height - [self.array[i]doubleValue] / self.maxValue * (self.frame.size.height-10));
}
}
CGContextDrawPath(ctx, kCGPathStroke);
}

我遇到的问题是,由于 drawRect: 方法中的 for 循环,我的 View Controller 需要几秒钟才能加载。我不想使用 viewDidAppear显示 embedGraphView 的方法,因为我可能还需要在 iPhone 旋转时重新绘制它。为了解决这个问题,有哪些解决方案?我可以使用 GCD,图像缓存吗?如何?

谢谢。

最佳答案

您每次都在绘制整个图表 drawRect:叫做。只绘制落在传入rect范围内的部分.

关于ios - drawRect中的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21953840/

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