iOS 畫虛線方法總結

前言

好幾天都沒有寫簡書了,主要是最近一直在做原型圖,六天的時間出了兩個項目的原型(PC+手機),結果累成狗,發現自己真有點像超人了。昨天寫了一個時間軸的小功能。在這里給大家分享一下,畫虛線的兩種方法,順便也幫助自己做一下記憶。

重寫drawRect方法
- (void)drawRect:(CGRect)rect{
     [super drawRect:rect];
     CGContextRef currentContext = UIGraphicsGetCurrentContext();
     //設置虛線顏色 
     CGContextSetStrokeColorWithColor(currentContext, [UIColor BlackColor].CGColor); 
     //設置虛線寬度 
     CGContextSetLineWidth(currentContext, 1); 
     //設置虛線繪制起點 
     CGContextMoveToPoint(currentContext, 0, 0); 
     //設置虛線繪制終點
     CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0);
     //設置虛線排列的寬度間隔:下面的arr中的數字表示先繪制3個點再繪制1個點
     CGFloat arr[] = {3,1}; 
     //下面最后一個參數“2”代表排列的個數。   
     CGContextSetLineDash(currentContext, 0, arr, 2); 
     CGContextDrawPath(currentContext, kCGPathStroke); 
}

看著這些代碼肯定有一部分人頭疼,因為一般開發繪圖部分用的比較少,特別是很少接觸這些東西的人,甚至對繪圖這部分的只是已經忘光了,所以在這里自己也腦補一下。
以下來自轉載

iOS的繪圖操作是在UIView類的drawRect方法中完成的,所以如果我們要想在一個UIView中繪圖,需要寫一個擴展UIView 的類,并重寫drawRect方法,在這里進行繪圖操作,程序會自動調用此方法進行繪圖。下面先說明一下繪圖,比如,你想繪制一個方塊,你需要寫一個類來擴展UIView并在drawRect方法中填入如下代碼:

- (void)drawRect:(CGRect)rect {      
    // Drawing code.      
    //獲得處理的上下文        
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    //設置線條樣式        
    CGContextSetLineCap(context, kCGLineCapSquare); 
    //設置線條粗細寬度        
    CGContextSetLineWidth(context, 1.0);             
    //設置顏色        
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    //開始一個起始路徑        
    CGContextBeginPath(context);         
    //起始點設置為(0,0):注意這是上下文對應區域中的相對坐標
    CGContextMoveToPoint(context, 0, 0);         
    //設置下一個坐標點 
    CGContextAddLineToPoint(context, 100, 100);         
    //設置下一個坐標點
    CGContextAddLineToPoint(context, 0, 150);       
    //設置下一個坐標點        
    CGContextAddLineToPoint(context, 50, 180);        
    //連接上面定義的坐標點 
    CGContextStrokePath(context);  
 }  

再說明一下重繪,重繪操作仍然在drawRect方法中完成,但是蘋果不建議直接調用drawRect方法,當然如果你強直直接調用此方法,當然是沒有效果的。蘋果要求我們調用UIView類中的setNeedsDisplay方法,則程序會自動調用drawRect方法進行重繪(調用setNeedsDisplay會自動調用drawRect)。
在UIView中,重寫drawRect: (CGRect) aRect方法,可以自己定義想要畫的圖案.且此方法一般情況下只會畫一次.也就是說這個drawRect方法一般情況下只會被掉用一次. 當某些情況下想要手動重畫這個View,只需要掉用[self setNeedsDisplay]方法即可.

drawRect的執行順序及注意

drawRect調是在Controller->loadView, Controller->viewDidLoad 兩方法之后掉用的.

  1. 如果在UIView初始化時沒有設置rect大小,將直接導致drawRect不被自動調用。

  2. 該方法在調用sizeThatFits后被調用,所以可以先調用sizeToFit計算出size。然后系統自動調用drawRect:方法。

  3. 通過設置contentMode屬性值為UIViewContentModeRedraw。那么將在每次設置或更改frame的時候自動調用drawRect:。

  4. 直接調用setNeedsDisplay,或者setNeedsDisplayInRect:觸發drawRect:,但是有個前提條件是rect不能為0.

以上1,2推薦;而3,4不提倡

  1. 若使用UIView繪圖,只能在drawRect:方法中獲取相應的contextRef并繪圖。如果在其他方法中獲取將獲取到一個invalidate的ref并且不能用于畫圖。drawRect:方法不能手動顯示調用,必須通過調用setNeedsDisplay 或者 setNeedsDisplayInRect ,讓系統自動調該方法。
  2. 若使用calayer繪圖,只能在drawInContext: 中(類似魚drawRect)繪制,或者在delegate中的相應方法繪制。同樣也是調用setNeedDisplay等間接調用以上方法。
  3. 若要實時畫圖,不能使用gestureRecognizer,只能使用touchbegan等方法來掉用setNeedsDisplay實時刷新屏幕
    轉載地址:
    http://blog.csdn.net/fww330666557/article/details/8647608
通過UIImage的繪圖方法來繪制
// 畫虛線
// 創建一個imageView 高度是你想要的虛線的高度 一般設為2
 _lineImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 2)]; 
// 調用方法 返回的iamge就是虛線 
_lineImg.image = [self drawLineByImageView:_lineImg]; 
// 添加到控制器的view上 
[self.view addSubview:_lineImg];


// 返回虛線image的方法
- (UIImage *)drawLineByImageView:(UIImageView *)imageView{ 
      UIGraphicsBeginImageContext(imageView.frame.size); //開始畫線 劃線的frame 
      [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)]; 
      //設置線條終點形狀 
      CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
      // 5是每個虛線的長度 1是高度 
      float lengths[] = {5,1}; 
      CGContextRef line = UIGraphicsGetCurrentContext(); 
      // 設置顏色 
      CGContextSetStrokeColorWithColor(line, [UIColor colorWithWhite:0.408 alpha:1.000].CGColor); 
      CGContextSetLineDash(line, 0, lengths, 2); //畫虛線
      CGContextMoveToPoint(line, 0.0, 2.0); //開始畫線
      CGContextAddLineToPoint(line, kScreenWidth - 10, 2.0);       

      CGContextStrokePath(line); 
      // UIGraphicsGetImageFromCurrentImageContext()返回的就是image 
      return UIGraphicsGetImageFromCurrentImageContext();
  }
通過CAShapeLayer方式繪制虛線
/**
  ** lineView:       需要繪制成虛線的view
  ** lineLength:     虛線的寬度
  ** lineSpacing:    虛線的間距 
  ** lineColor:      虛線的顏色
  **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{    
      CAShapeLayer *shapeLayer = [CAShapeLayer layer];
      [shapeLayer setBounds:lineView.bounds];
      [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];   
      [shapeLayer setFillColor:[UIColor clearColor].CGColor];  
      //  設置虛線顏色為blackColor    
      [shapeLayer setStrokeColor:lineColor.CGColor];   
      //  設置虛線寬度   
      [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];    
      [shapeLayer setLineJoin:kCALineJoinRound];    
      //  設置線寬,線間距
      [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];   
      //  設置路徑    
      CGMutablePathRef path = CGPathCreateMutable();   
      CGPathMoveToPoint(path, NULL, 0, 0);  
      CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
      [shapeLayer setPath:path];    
      CGPathRelease(path);   
      //  把繪制好的虛線添加上來   
      [lineView.layer addSublayer:shapeLayer];
  }

這部分代碼,有一個注意點:就是position和anchorPoint的區別,這點有興趣的可以去腦補一下。當然layer上的繪圖,我也感覺自己很low了,因為形式沒用過,所以基本上快忘光了,所以自己也需要花時間去腦補一下。
鏈接:http://wonderffee.github.io/blog/2013/10/13/understand-anchorpoint-and-position/

圖片平鋪(簡單暴力)
UIImageView *imgDashLineView =[[UIImageView alloc] initWithFrame:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)];
[imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian.png"]]];
[self.view addSubview:imgDashLineView];

寫完這篇博客,感覺自己現在繪圖基本忘光了,突然感覺好low的樣子……

歡迎關注我的個人微信公眾號,免費送計算機各種最新視頻資源!你想象不到的精彩!


0.jpg
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容