2011-12-22 113 views

回答

9

子类UView并重写drawRect绘制一个六边形,像这样:

- (void)drawRect:(CGRect)rect 
{  
    float polySize = 60; // change this 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context); 

    CGAffineTransform t0 = CGContextGetCTM(context); 
    t0 = CGAffineTransformInvert(t0); 
    CGContextConcatCTM(context, t0); 

    //Begin drawing setup 
    CGContextBeginPath(context); 
    CGContextSetRGBStrokeColor(context, 0, 0, 0, 1); 
    CGContextSetLineWidth(context, 2.0); 

    CGPoint center; 

    //Start drawing polygon 
    center = CGPointMake(160, 90.0); 
    CGContextMoveToPoint(context, center.x, center.y + polySize); 
    for(int i = 1; i < 6; ++i) 
    { 
     CGFloat x = polySize * sinf(i * 2.0 * M_PI/6); 
     CGFloat y = polySize * cosf(i * 2.0 * M_PI/6); 
     CGContextAddLineToPoint(context, center.x + x, center.y + y); 
    } 

    //Finish Drawing 
    CGContextClosePath(context); 
    CGContextDrawPath(context, kCGPathStroke); 
    CGContextRestoreGState(context); 
} 
+2

嗨,我刚刚测试的代码那里,但是这并不完全做一个UIView与六角形框架,这“简单”在框架内绘制一个六角形。 – IssamTP 2012-02-19 10:23:35

0

你可以创建一个UIView的子类,并在它的-(void)drawRect:方法中绘制一个六边形。或者使用的UIImageView六角

的图像