2

我有 UIView 子类,我想从 drawRect 中绘制一个 CGPath。我听说这是不可能的。我知道 CGPath 需要上下文。我试图用 newImage 给它上下文。我还认为我必须以不同的方式调用它,例如我在 CCLayer 中的代码,以便视图显示 drawRect 中的内容

- (void)createPath:(CGPoint)origin
{
CGSize size=CGSizeMake(320, 480);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsBeginImageContextWithOptions(size,YES,1.0f);
CGContextSaveGState(context);

UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();


CGRect newRect= CGRectMake(0, 0, 320, 480);
CGMutablePathRef path1 = CGPathCreateMutable();

CGPathMoveToPoint(path1, nil,100, 200);

CGPoint newloc = CGPointMake(300, 130);

CGPathMoveToPoint(path1, NULL, newloc.x, newloc.y);
CGPathAddLineToPoint(path1, NULL, newloc.x + 16,newloc.y + 38);
CGPathAddLineToPoint(path1, NULL, newloc.x + 49, newloc.y + 0);
CGPathAddLineToPoint(path1, NULL, newloc.x + 23,  newloc.y - 39);
CGPathAddLineToPoint(path1, NULL, newloc.x - 25,newloc.y - 40);
CGPathAddLineToPoint(path1, NULL, newloc.x -43, newloc.y + 0);
CGPathCloseSubpath(path1);

CGContextAddPath(context, path1);

CGContextSaveGState(context);
CGContextSetLineWidth(context, 10.0);
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
//Fill and stroke
CGContextDrawPath(context, kCGPathFillStroke);
//CGContextDrawImage(context, newRect, myImage.CGImage);

UIGraphicsEndImageContext();
CGContextRestoreGState(context);
CGPathRelease(path1); 
CGContextRelease(context);

}
4

1 回答 1

0

看看这是否对您有帮助。有一个 UIView 和 UIImageView 作为它的子视图。然后实现 touches 方法如下:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];   

    //Get touch point
    CGPoint currentPoint = [touch locationInView:drawImage];

    UIGraphicsBeginImageContext(self.frame.size);

    //drawImage is the UIImageView
    [drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)]; 

    //Line attributes
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 10.0);

    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.5, 1.0, 1.0);

    //Begin path
    CGContextBeginPath(UIGraphicsGetCurrentContext());

    CGPathMoveToPoint(drawPath, NULL, lastPoint.x, lastPoint.y);

    CGPathAddLineToPoint(drawPath, NULL, currentPoint.x, currentPoint.y);

    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());

    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
}

现在您可以看到 UIImageView 与您绘制的内容和 drawPath 将有您的路径。

于 2012-03-09T18:14:51.960 回答