2011-12-22 111 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六角

的圖像