2011-09-13 32 views
3

I'm相当新的编程,我已经有点半做了我的(简单)的应用程序,但我想知道如何绘制的图片在屏幕上(用户绘制的图片)和然后使用该图片的游戏,只是向左和向右移动(并检查其是否与其它图像碰撞)。借鉴了iPhone的目标C

我有这个..

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]; 
} 

但后来当我按下一个蓝色方形转到手指在屏幕上,但会费不画任何东西......

+0

所以你想画一个用户通过屏幕移动手指时的图片? – booleanBoy

+0

是啊........... – miniman

回答

1

绘图用户生成图片与可可触摸是一个2步骤的过程。 UIView只会在清除所有之前用户绘制的东西之后绘制最新的触摸。

一种可能的解决方案是将所有的用户触摸保存在历史阵列和(重新)绘制个个进入视图添加任何新的触摸之后。但是,这可能会非常缓慢,这取决于所需的图纸数量。

另一种可能的2步的方法是创建自己的位图绘制上下文。首先在这个上下文中绘制最新的东西,如果配置正确,它将保留绘图的较旧部分,然后将此上下文绘制到UIView中(或将位图转换为在视图上的图层中显示的图像)。

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; 

和声明属性...

@属性(非原子,保留)UIBezierPath * currentPath;

在initWIthFrame方法

内如果块添加这些行

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

创建viewcontroler类再加入在方法的loadView这些代码行..

mainView=[[sampleView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)]; 
mainView.backgroundColor=[UIColor whiteColor]; 
self.view=mainView; 

其中sampleView是UIView子类ù创建B4 ....

希望这会有所帮助...

+0

对不起我的格式化方式... – booleanBoy

+0

booleanBoy,你还没有声明mainView ... – miniman

+0

你好吗?......... – miniman