在Objective C中在iPhone上进行绘图

3

我对编程很新,我已经制作了一个(简单)的应用程序,但我想知道如何在屏幕上绘制图片(用户绘制图片),然后将该图像用于游戏中只向左右移动(并检查它是否与另一幅图像碰撞)。

我有这个...

float pointx;
float pointy;


- (void)drawRect:(CGRect)rect {
CGColorRef blue = [[UIColor blueColor] CGColor];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.bounds);

CGContextSetFillColorWithColor(context, blue);
CGContextFillRect(context, CGRectMake(pointx, pointy, 10, 10));

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch=[[event allTouches]anyObject];
CGPoint point = [touch locationInView:touch.view];
pointx = point.x;
pointy = point.y;
[self setNeedsDisplay];
}

但是,当我在屏幕上按下时,蓝色正方形会移动到手指位置,但不会绘制任何内容...

你想在用户通过屏幕滑动手指时绘制一张图片吗? - stack2012
2个回答

2
创建一个继承自UIView的类...然后在该类中添加以下代码...
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
[currentPath moveToPoint:(gestureStartPoint)];

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentPosition = [touch locationInView:self]; 
[currentPath addLineToPoint:(currentPosition)];
[self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect {
[[UIColor redColor] set];
[currentPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

在头文件中声明以下内容...

CGPoint gestureStartPoint,currentPosition;
UIBezierPath *currentPath;

声明一个属性...

@property(nonatomic,retain)UIBezierPath *currentPath;

在initWithFrame方法中的if块内添加以下行:

currentPath = [[UIBezierPath alloc]init];
currentPath.lineWidth=3;

创建一个视图控制器类,然后在loadView方法中添加以下代码:
mainView=[[sampleView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
mainView.backgroundColor=[UIColor whiteColor];
self.view=mainView;

其中sampleView是您之前创建的UIView子类...

希望这可以帮到您...


mainView是全局的...我已经在头文件中声明了它....希望你能理解.... - stack2012
为什么你不使用 C,却声明了它? - miniman
我发誓你只声明了:CGPoint gestureStartPoint, currentPosition; CGContextRef c; UIBezierPath *currentPath; - miniman
不,你不需要合成当前位置... - stack2012
抱歉...你是对的...没有必要使用CGContextRef *c....我已经删除了它..现在请检查编辑后的答案... - stack2012
显示剩余3条评论

1
使用Cocoa Touch绘制用户生成的图片是一个2步骤的过程。UIView只会在清除了之前用户绘制的所有内容后,绘制最新的触摸。
一种可能的解决方案是将所有用户触摸保存在历史数组中,并在添加任何新触摸后重新绘制它们到视图中。但这可能会非常慢,具体取决于所需绘制的数量。
另一种可能的2步方法是创建自己的位图绘制上下文。首先将最新的东西绘制到此上下文中,如果正确配置,则该上下文将保留绘图的旧部分,然后将此上下文绘制到UIView中(或将位图转换为在视图上显示的图像层)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接