Drawing in UIScrollView

2019-09-08 09:34发布

I am currently working on a project that enables you to draw with touches in a scrollview. The only problem is, it doesn't let me draw to the bottom part of the scrollview. I am thinking it has something to do with UIGraphicsgetCurrentContext(). Any help will be awesome! Heres what I have so far

- (void)drawRect:(CGRect)rect {
    //Here
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(1630, 2400), YES, 5);
    __block CGContextRef context = UIGraphicsGetCurrentContext();
    //CGContextAddRect(context, CGRectMake(0, 0, 1024, 1620));
    //[contentView.layer renderInContext:context];
    CGContextSaveGState(context);
    CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextSetLineWidth(context, 4.0f);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    [[ProblemStore sharedProblemStore] mapCurrentSolutionStrokes:^(SolutionStroke *stroke,   NSUInteger strokeNum) {
      [self drawStroke:stroke inContext:context];
    }];
    CGContextRestoreGState(context);
    UIGraphicsEndImageContext();
}

1条回答
混吃等死
2楼-- · 2019-09-08 10:03

If this drawRect method is for some UIView subclass, you can simplify it:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextSetLineWidth(context, 4.0f);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    [[ProblemStore sharedProblemStore] mapCurrentSolutionStrokes:^(SolutionStroke *stroke,   NSUInteger strokeNum) {
        [self drawStroke:stroke inContext:context];
    }];
}

You generally use the UIGraphicsBeginImageContextWithOptions when you want to render some view and retrieve an image with UIGraphicsGetImageFromCurrentImageContext, but you don't generally use UIGraphicsBeginImageContextWithOptions in your custom view's drawRect, itself. I would separate the drawRect functionality from the image saving logic (assuming you even need/want the latter).

So, I personally would create a custom view of the appropriate size (e.g. 1,630 x 2,400), add it to the scroll view, and use the above as the drawRect for that custom view.

In terms of why your rendition is not drawing down to the bottom of the scroll view, I suspect it's related to your choice of scale of 5 for your UIGraphicsBeginImageContextWithOptions. Usually you use 1 (non-retina), 2 (retina), or 0 (use the scale from the main screen).

As an aside, you don't need the __block qualifier for your CGContextRef. You can access the context variable without it.

查看更多
登录 后发表回答