iOS給一個view添加虛線邊框


/**

 * 此方法作用:給一個矩形視圖增加四條矩形虛線邊框

 *

 * parma:superView:需要加載的父視圖

 */

#define padding 20

 

- (void)addDottedLineFromImageView:(UIView *)superView{

    CGFloat w = superView.frame.size.width;

    CGFloat h = superView.frame.size.height;

    

//創建四個imageView作邊框

    for (NSInteger i = 0; i<4; i++) {

        UIImageView *imageView = [[UIImageView alloc] init];

   imageView.backgroundColor = [UIColor clearColor];

        if (i == 0) {

            imageView.frame = CGRectMake(0, 0, w, padding);

        }else if (i == 1){

            imageView.frame = CGRectMake(0, 0, padding, h);

        }else if (i == 2){

            imageView.frame = CGRectMake(0, h - padding, w, padding);

        }else if (i == 3){

            imageView.frame = CGRectMake(w - padding, 0, padding, h);

        }

        [superView addSubview:imageView];

        

        UIGraphicsBeginImageContext(imageView.frame.size);   //開始畫線

        [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];

        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);  //設置線條終點形狀

        

        CGFloat lengths[] = {10,5};

        CGContextRef line = UIGraphicsGetCurrentContext();

        CGContextSetStrokeColorWithColor(line, [UIColor blackColor].CGColor);

        CGContextSetLineDash(line, 0, lengths, 2);  //畫虛線 

        CGContextMoveToPoint(line, 0, 0);    //開始畫線

        

        if (i == 0) {

            CGContextAddLineToPoint(line, w - padding, 0);

        }else if (i == 1){

            CGContextAddLineToPoint(line, 0, w);

        }else if (i == 2){

            CGContextMoveToPoint(line, 0, padding);

            CGContextAddLineToPoint(line, w, padding);

        }else if (i == 3){

            CGContextMoveToPoint(line, padding, 0);

            CGContextAddLineToPoint(line, padding, w);

        }

        

        CGContextStrokePath(line);

        imageView.image = UIGraphicsGetImageFromCurrentImageContext();

    }

}

 


免責聲明!

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



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