簡體   English   中英

如果原始CGPoints丟失,如何將存儲的CGPath重繪為Bezier路徑

[英]How to redraw a stored CGPath as a Bezier path if the original CGPoints are lost

如果未存儲原始CGPoints,如何將存儲的CGPath重繪為Bezier路徑?

這是代碼,但它不起作用(路徑在標准模式下重繪而不是在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);

您可以使用UIBezierPath的以下方法:

+ (UIBezierPath *)bezierPathWithCGPath:(CGPathRef)CGPath

重用CGPath是有效的。 檢查此示例在UIViewController添加TestView並鏈接UIButton以在使用[_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

Swift 3.0版本的atxe答案:

let myCGPath: CGPath = // stored CGPath or path taken from another object
let bezierPath = UIBezierPath(cgPath: myCGPath)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM