[英]Drawing in Objective-C
我知道您可以使用CoreGraphics在視圖中繪制。 但這僅限於drawRect函數。
我想知道您是否可以使用一個具有兩個按鈕(上,下,左,右)的應用程序。 而且,當用戶選擇按鈕時,它會從原始點沿剛剛選擇了20像素的按鈕方向繪制一條線。
例如 :
假設用戶點擊了右鍵:
Start
+----------+
然后他們按下按鈕:
Start
+----------+
|
|
|
|
+
然后他們按左鍵
+----------+
|
|
|
|
+----------+
等等,
可以使用石英完成此操作,還是需要學習OpenGL之類的知識?
使用UIBezierPath
這非常簡單:
這是一個快速,基本的示例,如何繪制它
MoveView
,與公共方法-moveToDirection:
-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
這就是我得到的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.