iOS 利用drawRect方法使用CGContextRef繪制帶箭頭的氣泡view

很簡單的一份代碼,相信各位吳彥祖以及梁朝偉都會只是會有點(diǎn)浪費(fèi)時(shí)間,廢話不多說,上代碼。

- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    CGSize arrowSize = CGSizeMake(10, 10);
    CGFloat cornerRadius = 4;// 圓角角度
    
    CGFloat selfWidth = rect.size.width;
    CGFloat selfHeight = rect.size.height;
    
    
    // 獲取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 矩形填充顏色
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    
    CGContextMoveToPoint(context, cornerRadius, 0);
    
    
    CGFloat rightContetMaxX = selfWidth - arrowSize.width;
    CGContextAddArcToPoint(context, rightContetMaxX, 0, rightContetMaxX, selfHeight/2 - arrowSize.height/2, cornerRadius);
    
    
    CGContextAddLineToPoint(context, rightContetMaxX, selfHeight/2 - arrowSize.height/2);
    CGContextAddArcToPoint(context, selfWidth, selfHeight/2, rightContetMaxX, selfHeight/2 + arrowSize.height/2, 2);
    
    CGContextAddArcToPoint(context, rightContetMaxX, selfHeight/2 + arrowSize.height/2, rightContetMaxX, selfHeight, 2);
    
    CGContextAddArcToPoint(context, rightContetMaxX, selfHeight, 0, selfHeight, cornerRadius);
    CGContextAddArcToPoint(context, 0, selfHeight, 0, selfHeight - cornerRadius, cornerRadius);
    CGContextAddArcToPoint(context, 0, 0, cornerRadius, 0, cornerRadius);
    
    CGContextDrawPath(context, kCGPathFill);
    // 必須要在調(diào)用super之前繪制完成否則會出現(xiàn)當(dāng)前view中的文字無法顯示問題。
    [super drawRect:rect];
}

simulator_screenshot_2C49A3B5-B9AA-47E6-99DC-4D5C98BA1032.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容