我正在尝试画一个六边形,并且已经在网上关注了几个教程。但我必须做错事,因为我的结果总是不完整的。最初我认为这是因为我使视图框架太小,但即使我将w / h提高到800,我仍然得到相同的结果。这是我的代码:
FEG_Map是一个UIView,它在viewcontroller中设置并保存十六进制网格。
@implementation FEG_Map
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void) addHex {
float rowX = 400.0;
float rowY = 10.0;
FEG_Hex* thisHex = [[FEG_Hex alloc] initWithFrame:CGRectMake(rowX, rowY, 800.0, 800.0)];
thisHex.backgroundColor = [UIColor clearColor];
[self addSubview:thisHex];
}
在FEG_Hex我骑过drawRect并添加:
- (void)drawRect:(CGRect)rect {
//create mutable path
CGMutablePathRef path = CGPathCreateMutable();
//go to start point
CGPathMoveToPoint(path, nil, _origin.x, _origin.y);
//move along hex path
CGPoint newloc = CGPointMake(_origin.x - 20, _origin.y + 42);
CGPathMoveToPoint(path, NULL, newloc.x, newloc.y);
CGPathAddLineToPoint(path, NULL, newloc.x + 16,newloc.y + 38);
CGPathAddLineToPoint(path, NULL, newloc.x + 49, newloc.y + 0);
CGPathAddLineToPoint(path, NULL, newloc.x + 23, newloc.y - 39);
CGPathAddLineToPoint(path, NULL, newloc.x - 25,newloc.y - 40);
CGPathAddLineToPoint(path, NULL, newloc.x -43, newloc.y + 0);
CGPathCloseSubpath(path);
//add a context
CGContextRef context = UIGraphicsGetCurrentContext();
//add path to context
CGContextAddPath(context, path);
//stroke path
CGContextSetLineWidth(context, 2.0);
//set the stroke color
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextStrokePath(context);
}
我的结果是:
答案 0 :(得分:0)
更改您的代码:
CGPoint newloc = CGPointMake(_origin.x - 20, _origin.y + 42);
到
CGPoint newloc = CGPointMake(_origin.x + 42, _origin.y + 20);
你会看到你的六边形。但这不正确。
要获得更正确的六边形,请使用以下代码:
CGPoint newloc = CGPointMake(_origin.x + 46, _origin.y + 20);
CGPathMoveToPoint(path, NULL, newloc.x + 23, newloc.y + 40);
CGPathAddLineToPoint(path, NULL, newloc.x + 46, newloc.y + 0);
CGPathAddLineToPoint(path, NULL, newloc.x + 23, newloc.y - 40);
CGPathAddLineToPoint(path, NULL, newloc.x - 23, newloc.y - 40);
CGPathAddLineToPoint(path, NULL, newloc.x - 46, newloc.y + 0);
CGPathAddLineToPoint(path, NULL, newloc.x - 23, newloc.y + 40);
CGPathCloseSubpath(path);