IOS:在视图中绘制图像

前端之家收集整理的这篇文章主要介绍了IOS:在视图中绘制图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个代码在视图中着色:

UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:drawImage];

    UIGraphicsBeginImageContext(drawImage.frame.size);
    [drawImage.image drawInRect:CGRectMake(0,drawImage.frame.size.width,drawImage.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(),kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(),size);

      CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),r,g,b,a);

    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(),lastPoint.x,lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(),currentPoint.x,currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

我的问题是我想要用一个点来着色,但我想使用一个重复的特定图像(作为一个png图像)
可能吗?

解决方法

加载单个UIImage并绘制它很容易:

UIImage *brushImage = [UIImage imageNamed:@"brush.png"];
[brushImage drawAtPoint:CGPointMake(currentPoint.x-brushImage.size.width/2,currentPoint.y-brushImage.size.height/2)];

这将每个周期仅绘制一次图像,而不是连续线.如果您想要画笔的实线,请参阅Objective C: Using UIImage for Stroking.

这可能会在每次调用方法时最终加载图像文件,从而使其变慢.虽然[UIImage imageNamed:]的结果经常被缓存,但我的代码可以通过存储刷子以便以后重用来改进.

说到性能,请在旧设备上进行测试.正如所写,它适用于我的第二代iPod touch,但任何添加都可能使它在第二代和第三代设备上口吃.由@Armaan推荐的Apple的GLPaint示例使用OpenGL进行快速绘图,但涉及的代码要多得多.

此外,您似乎在视图中进行交互(touchesBegan:,touchesMoved:,touchesEnded :),然后将其内容绘制到drawImage,可能是UIImageView.可以存储绘画图像,然后将此视图的图层内容设置为该图像.这不会改变性能,但代码会更清晰.如果继续使用drawImage,请使用其ivar通过属性访问它.

猜你在找的Xcode相关文章