如何在使用`drawInRect:blendMode:`的UIView上优化CPU和RAM使用?

时间:2016-08-29 00:40:50

标签: ios xcode optimization uiview uibezierpath

我正在开发一个绘图应用程序,它允许用户在drawInRect:blendMode方法中drawRect在UIView中绘制的图像上仅绘制一个UIBezier路径,并且它使用超过80%的CPU和55MB的RAM,当我在时间分析器中追踪它时,它是导致大部分CPU使用率的drawInRect:blendMode方法。我已经做了很少的优化但是我可以做什么进一步优化来绘制使用[image drawInRect:Rect];绘制的UIImage以及用户在其上绘制的UIBezierpath? 提前谢谢。

@interface InsideView(){
    CGRect imageRect;
    CGRect targetBounds;
}
@property (strong, nonatomic) NSMutableArray *strokes;
@property (nonatomic, strong) UIImage * img;
@property (nonatomic, strong) UIBezierPath *drawingPath;
@end

@implementation InsideView

-(void)drawRect:(CGRect)rect{
    targetBounds = self.layer.bounds;
    imageRect = AVMakeRectWithAspectRatioInsideRect(self.img.size,targetBounds);
    [self.img drawInRect:imageRect];

    for (int i=0; i < [self.strokes count]; i++) {
         UIBezierPath* tmp = (UIBezierPath*)[self.strokes  objectAtIndex:i];
         [[UIColor whiteColor] setStroke];
         [tmp stroke];
    }
}
- (CGRect)segmentBoundsFrom:(CGPoint)point1 to:(CGPoint)point2
{
    CGRect dirtyPoint1 = CGRectMake(point1.x-10, point1.y-10, 50, 50);
    CGRect dirtyPoint2 = CGRectMake(point2.x-10, point2.y-10, 50, 50);
    return CGRectUnion(dirtyPoint1, dirtyPoint2);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    self.drawingPath = [UIBezierPath bezierPath];
    self.drawingPath.lineWidth = 10;
    self.drawingPath.lineCapStyle = kCGLineCapRound;
    self.drawingPath.lineJoinStyle = kCGLineJoinRound;
    [self.drawingPath moveToPoint:[[touches anyObject] locationInView:self]];
    [self.strokes addObject:self.drawingPath];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    //Dirty Rect Calculations
    CGPoint prevPoint = CGPathGetCurrentPoint(self.drawingPath.CGPath);
    CGPoint point = [[touches anyObject] locationInView:self];
    CGRect dirty = [self segmentBoundsFrom:prevPoint to:point];

    [[self.strokes lastObject] addLineToPoint:point];
    [self setNeedsDisplayInRect:dirty];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [[self.strokes lastObject] addLineToPoint:[[touches anyObject] locationInView:self]];
    [self setNeedsDisplay];
}

0 个答案:

没有答案