2014-09-21 82 views
0

我知道你可以使用CoreGraphics繪製視圖。但它僅限於drawRect函數。繪製Objective-C

我想知道你是否可以有一個應用程序,它有幾個按鈕(上,下,左,右)。並且當用戶選擇該按鈕時,它從原始點按照剛纔按20像素選擇的按鈕方向繪製一條線。

例如:

假定用戶點擊右邊按鈕:

   Start 
       +----------+ 

然後他們擊中了向下按鈕:

   Start 
       +----------+ 
          | 
          | 
          | 
          | 
          + 

然後他們擊中左按鈕

   +----------+ 
          | 
          | 
          | 
          | 
       +----------+ 

等,

這可以使用石英或我需要學習像OpenGL的東西嗎?

+0

您可以使用UIBezier路徑。 – WMios 2014-09-21 06:09:03

+0

爲什麼不在'-drawRect:'中做? – 2014-09-21 06:40:25

回答

2

隨着UIBezierPath它很容易:

這是一個快速,簡單的例子如何繪製它

  1. UIView子類比方說MoveView,與公共方法-moveToDirection:
  2. 在瀏覽商店的方向一個陣列
  3. 每當新的方向添加我們呼籲-setNeedsDisplay畫出新線

注:只是簡單的例子,相信你需要對其進行修改和實施一些限制

MoveView.h

#import <UIKit/UIKit.h> 

typedef NS_ENUM(NSInteger, MovieViewDirection) { 
    MoveViewDirectionRight, 
    MoveViewDirectionLeft, 
    MoveViewDirectionUp, 
    MoveViewDirectionDown 
}; 

@interface MoveView : UIView 

- (void)moveInDirection:(MovieViewDirection)direction; 

@end 

MoveView.m

#import "MoveView.h" 

static const CGFloat kMoveViewStepDistance = 20.0f; 

@interface MoveView() 

@property (nonatomic, strong) NSArray *movingDirections; 

@end 

@implementation MoveView 

#pragma mark - Services 

- (void)drawRect:(CGRect)rect { 

    UIBezierPath* bezierPath = UIBezierPath.bezierPath;   

    CGPoint currentPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));   
// Start point by default it is a center 
    [bezierPath moveToPoint: currentPoint]; 

    for (NSNumber *direction in self.movingDirections) { 
     CGPoint moveToPoint; 
     switch (direction.integerValue) { 
      case MoveViewDirectionLeft: 
       moveToPoint = CGPointMake(currentPoint.x - kMoveViewStepDistance, currentPoint.y); 
       break; 
      case MoveViewDirectionRight: 
       moveToPoint = CGPointMake(currentPoint.x + kMoveViewStepDistance, currentPoint.y); 
       break; 
      case MoveViewDirectionUp: 
       moveToPoint = CGPointMake(currentPoint.x, currentPoint.y - kMoveViewStepDistance); 
       break; 
      case MoveViewDirectionDown: 
       moveToPoint = CGPointMake(currentPoint.x, currentPoint.y + kMoveViewStepDistance); 
       break;     
      default: 
       break; 
     } 
     currentPoint = moveToPoint; 
     [bezierPath addLineToPoint: moveToPoint]; 
    } 

    [UIColor.redColor setStroke]; 
    bezierPath.lineWidth = 1; 
    [bezierPath stroke]; 

} 

#pragma mark - Public 
- (void)moveInDirection:(MovieViewDirection)direction { 
    [self addMoveStepInDirection:direction]; 
    [self setNeedsDisplay]; 
} 

#pragma mark - Private 

- (void)addMoveStepInDirection:(MovieViewDirection)direction { 
    NSMutableArray *steps = [NSMutableArray arrayWithArray:self.movingDirections]; 
    [steps addObject:[NSNumber numberWithInteger:direction]]; 
    self.movingDirections = steps; 
} 

@end 

這是我得到了什麼:

enter image description here

+0

非常感謝一噸。 – 2014-09-22 10:04:11