简体   繁体   English

如何在不影响背景图像的情况下在UIImageView上绘制?

[英]How to draw on UIImageView without affecting the background image?

I have single view controller application. 我有单视图控制器应用程序。 It contains UIImageView and on user touch it draws on the screen. 它包含UIImageView,并在用户触摸时在屏幕上绘制。 This part works fine. 这部分工作正常。 In view did load method of viewcontroller I set up a different image as background image. 考虑到viewcontroller的加载方法,我设置了不同的图像作为背景图像。 And I set that image view background as clear color. 我将图像视图背景设置为清晰的颜色。 Now when I try to erase something from UIImageView, i also erase the view controller background view. 现在,当我尝试从UIImageView删除某些内容时,我还将删除视图控制器的背景视图。 How can I avoid this ? 如何避免这种情况?

Here is my code To set an background for viewcontroller in viewDidLoad() 这是我的代码在viewDidLoad()中为viewcontroller设置背景

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bacground.png"]];
image.backgroundColor = [UIColor clearColor];    

To draw on screen in touchesMoved method 在touchesMoved方法上在屏幕上绘制

UIGraphicsBeginImageContext(image.frame.size);
[image.image drawInRect:CGRectMake(0, 0, image.frame.size.width, image.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), lineWidth);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), self.drawcolor.CGColor);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
image.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

To erase I am just setting drawcolor to whiteColor. 为了擦除,我只是将drawcolor设置为whiteColor。

To set the image for background use following and then try to draw the other image on view 若要将图像设置为背景使用,然后尝试在视图上绘制其他图像

            UIImageView *background = [[UIImageView alloc]initWithImage:[UIImage imageNamed: @"backipad.png"]];
self.view = background;

Try with above, I have not came across such problem ever but I think this will work for you..and 尝试以上,我从来没有遇到过这样的问题,但我认为这将为您工作。

 background.userInteractionEnabled = YES;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM