IOS開發 圖形繪制,繪制線條,矩形,和垂直和居中繪制文字


概述

  吐槽下IOS下 的圖形繪圖,代碼冗長,不得不自己重新封裝方法。整理形成本文。

繪制線

// 繪制直線
+ (void)toDrawLineFromX:(CGFloat)x1 Y:(CGFloat)y1 toX:(CGFloat)x2 toY:(CGFloat)y2 context:(CGContextRef)con{
    CGContextMoveToPoint(con, x1, y1);
    CGContextAddLineToPoint(con, x2, y2);
    CGContextSetLineWidth(con, 1);
    CGContextStrokePath(con);
}

 

繪制矩形

//繪制矩形 ,fillColor填充色
+ (void)toDrawRect:(CGRect)rectangle color:fillColor context:(CGContextRef)ctx{
    
    //創建路徑並獲取句柄
    CGMutablePathRef
    path = CGPathCreateMutable();
    //將矩形添加到路徑中
    CGPathAddRect(path,NULL,
                  rectangle);
    //獲取上下文
    //將路徑添加到上下文
    
    CGContextAddPath(ctx,
                     path);
    
    //設置矩形填充色
    [fillColor setFill];
    //矩形邊框顏色
    [[UIColor
      whiteColor] setStroke];
    //邊框寬度
    CGContextSetLineWidth(ctx,0);
    //繪制
    CGContextDrawPath(ctx,
                      kCGPathFillStroke);
    CGPathRelease(path);
}

 

垂直和居中繪制文字

///繪制文字,rect1指定矩形,繪制文字在這個矩形水平和垂直居中
+ (void)toDrawTextWithRect:(CGRect)rect1 str:(NSString*)str1 context:(CGContextRef)context{
    if( str1 == nil || context == nil)
        return;
    
    CGContextSetLineWidth(context, 1.0);
    CGContextSetRGBFillColor (context, 0.01, 0.01, 0.01, 1);
    
    //段落格式
    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    textStyle.lineBreakMode = NSLineBreakByWordWrapping;
    textStyle.alignment = NSTextAlignmentCenter;//水平居中
    //字體
    UIFont  *font = [UIFont boldSystemFontOfSize:22.0];
    //構建屬性集合
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:textStyle};
    //獲得size
    CGSize strSize = [str1 sizeWithAttributes:attributes];
    CGFloat marginTop = (rect1.size.height - strSize.height)/2;
    //垂直居中要自己計算
    CGRect r = CGRectMake(rect1.origin.x, rect1.origin.y + marginTop,rect1.size.width, strSize.height);
    [str1 drawInRect:r withAttributes:attributes];
}

 

如何使用

  假設把上面的方法放入到一個類  DrawUtil 中,我們可以通過 DrawUtil 來調用方法。

  定義: #define drawLine(x1,y1,x2,y2,con) [DrawUtil toDrawLineFromX:x1 Y:y1 toX:x2 toY:y2 context:con]

   //獲得上下文

  CGContextRef con = UIGraphicsGetCurrentContext();

     CGContextClearRect(con, rect);

  //畫線,

  drawLine(x,y,x+rectWidth,y,con);

  //矩形

  [DrawUtil toDrawRect:CGRectMake(x*unitWidth+1, y*unitHeight+1,unitWidth-1, unitHeight-1) color:[UIColor whiteColor] context:con];

  //文字

  [DrawUtil toDrawTextWithRect:rect1 str:@"你" context:context];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM