2014-09-21 49 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