我有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);
}
答案 0 :(得分:0)
看看这对你有帮助。使用UIImageView作为子视图的UIView。然后实现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将拥有您的路径。