2013-05-27 30 views
3

我期待有一些標記爲紅色的標記,但不知道它是否可以完成。書法繪圖IOS Coregraphics

它看起來像使用書法筆標記。

enter image description here

試行下面的代碼由「安德烈」作爲回答,我得到的空間下面的輸出,同時繪製。

enter image description here

刷圖像可以在這裏找到使用的是enter image description here

製作的代碼的進一步變化,我發現還是我沒能得到預期的結果。 這裏我試圖填充當前點和下一點之間存在的路徑。

- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 


    CGFloat w=5.0; 
    CGFloat h=2.0; 
    CGContextRef context=UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor); 

    for(int i=0;i<self.positions.count;i++){ 
     CGPoint point=[[self.positions objectAtIndex:i] CGPointValue]; 

     CGFloat x=point.x-(w/2.0); 
     CGFloat y=point.y-(h/2.0); 
     CGContextFillRect(context, CGRectMake(x, y, w, h)); 
     if(i+1<self.positions.count){ 
      CGPoint nextPoint=[[self.positions objectAtIndex:(i+1)] CGPointValue]; 
      CGMutablePathRef myPath=CGPathCreateMutable(); 
      CGPathMoveToPoint(myPath, NULL, x, y); 
      CGFloat x1=nextPoint.x-(w/2.0); 
      CGFloat y1=nextPoint.y-(h/2.0); 

      CGPathAddLineToPoint(myPath, NULL, x1, y1); 
      CGPathAddLineToPoint(myPath, NULL, w, y1); 
      CGPathAddLineToPoint(myPath, NULL, w, y); 
      CGPathCloseSubpath(myPath); 
      CGContextFillPath(context); 
     } 
    } 
} 

回答

2

這些圖像可以通過在子類UIView與重寫drawRect:消息繪製圖像來完成。您還需要添加某種觸摸處理程序來捕捉觸摸。因此,這裏是一些代碼:

@interface DrawingView() 

@property (nonatomic, strong) NSMutableArray *positions; 

@end 

@implementation DrawingView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     [self awakeFromNib]; 
    } 
    return self; 
} 

- (void)awakeFromNib 
{ 
    self.positions = [[NSMutableArray alloc] init]; 
} 

- (void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 

    UIImage *brushImage = [UIImage imageNamed:@"brush.png"]; 
    for (NSValue *object in self.positions) { 
     CGPoint point = [object CGPointValue]; 
     [brushImage drawAtPoint:CGPointMake(point.x - brushImage.size.width/2.0, point.y - brushImage.size.height/2.0)]; 
    } 
} 

- (void)addPoint:(CGPoint)point 
{ 
    [self.positions addObject:[NSValue valueWithCGPoint:point]]; 

    [self setNeedsDisplay]; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    [self addPoint:[touch locationInView:self]]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    [self addPoint:[touch locationInView:self]]; 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    [self addPoint:[touch locationInView:self]]; 
} 

@end 

你只需要你想要的任何地方創建一個適當的brush.png,並把這些觀點。

+0

從來沒有想過這會很容易畫出來。嘿順便說一句,當我編碼我發現有幾個空位被遺漏,這不應該發生,因爲我們不斷更新touchesMoved: – weber67

+0

@ weber67' touchesMoved'會跳過一些位置。你必須記住最後一個位置並插入它們之間的位置。 – Sulthan

+0

@ weber67你應該使用上面提到的Sulthan的某種內插。正確的邏輯是實現插入的線條繪圖,您可以從觸摸中獲得點。但複雜的數字可能會變慢。 –