2

如果未存储原始 CGPoints,如何将存储的 CGPath 重绘为 Bezier 路径?

这是代码,但它不起作用(在标准模式下重绘路径而不是在贝塞尔模式下):

CGMutablePathRef UpathFREEHAND = CGPathCreateMutable();
CGPoint firstPointFH = [[pointArray objectAtIndex:0] CGPointValue];
CGPathMoveToPoint(UpathFREEHAND, NULL, firstPointFH.x, firstPointFH.y);

for (int i = 0; i < [pointArray count]; i++)
    {
        CGPathAddLineToPoint(UpathFREEHAND, NULL, [[pointArray objectAtIndex:i] CGPointValue].x, 
        [[pointArray objectAtIndex:i] CGPointValue].y);
    }

CGMutablePathRef _TempPathForUndo = UpathFREEHAND;

//Add PATH object to array
[UPath addObject:CFBridgingRelease(_TempPathForUndo)];

//Load PATH object from array
_TTempPathForUndo = (__bridge CGMutablePathRef)([UPath objectAtIndex:i]);

// Now create the UIBezierPath object.
UIBezierPath *bp;
bp = [UIBezierPath bezierPath];
bp.CGPath = _TTempPathForUndo;

CGContextAddPath(context, bp.CGPath);
//Color, Brush Size parameters, Line cap parameters..
CGContextStrokePath(context);
4

2 回答 2

3

您可以使用以下方法UIBezierPath

+ (UIBezierPath *)bezierPathWithCGPath:(CGPathRef)CGPath

a 的重用CGPath是有效的。检查此示例添加TestViewaUIViewController并链接 aUIButton以在单击它时强制重绘[_testView setNeedsDisplay]

// TestView.h

#import <UIKit/UIKit.h>

@interface TestView : UIView {

    CGMutablePathRef _path;
    BOOL _nextDraws;
}

@end

// TestView.m

#import "TestView.h"

@implementation TestView

- (void)drawRect:(CGRect)rect {

    BOOL firstDraw = !_nextDraws;
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    if (firstDraw) {
        NSLog(@"first draw");

        _path = CGPathCreateMutable();
        CGPathMoveToPoint(_path, NULL, 0, 0);
        CGPathAddLineToPoint(_path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGPathCloseSubpath(_path);
        CGContextAddPath(ctx, _path);
        CGContextSetStrokeColorWithColor(ctx,[UIColor whiteColor].CGColor);
        CGContextStrokePath(ctx);

        _nextDraws = YES;
    }
    else {
        NSLog(@"next draws");

        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextClearRect(ctx, rect);
        UIBezierPath * bezierPath = [UIBezierPath bezierPathWithCGPath:_path];
        CGContextAddPath(ctx, bezierPath.CGPath);
        CGContextSetStrokeColorWithColor(ctx,[UIColor whiteColor].CGColor);
        CGContextStrokePath(ctx);
    }
}

- (void)dealloc {
    CGPathRelease(_path);
    [super dealloc];
}

@end
于 2012-10-21T09:47:13.610 回答
1

atxe 的 Swift 3.0 版本的回答:

let myCGPath: CGPath = // stored CGPath or path taken from another object
let bezierPath = UIBezierPath(cgPath: myCGPath)
于 2017-06-09T17:33:33.610 回答