2011-09-13 33 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