隨筆-iOS學習簡單繪圖
阿新 • • 發佈:2019-01-08
在iOS中,圖形的繪製是基於UIView來繪製的,所以,我們要先建立一個用來繪製圖形的UIView類。
UIView的類中有一個方法是專門用來繪製圖形的:
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
我嘗試了一些簡單的圖形繪製命令:
/* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. */ - (void)drawRect:(CGRect)rect { // Drawing code //獲取當前裝置的上下文(畫布) CGContextRef context = UIGraphicsGetCurrentContext(); //畫筆移到某一點 CGContextMoveToPoint(context, 0, 0); //從一點到某一點畫條線 CGContextAddLineToPoint(context, 100, 100); //給線渲染塗色 CGContextStrokePath(context); //矩形框 CGContextAddRect(context, CGRectMake(0, 0, 100, 100)); CGContextStrokeRect(context, CGRectMake(0, 0, 100, 100)); //實心矩形 CGContextFillRect(context, CGRectMake(100, 100, 100, 100)); //空心圓 CGContextStrokeEllipseInRect(context, CGRectMake(100, 200, 100, 100)); //實心圓 CGContextFillEllipseInRect(context, CGRectMake(100, 300, 100, 100)); //繪製文字 NSString * str = @"Hello world!"; [str drawAtPoint:CGPointMake(125, 400) withAttributes:nil]; //繪製圖片 [img drawAtPoint:CGPointMake(100, 500)]; [img drawAsPatternInRect:CGRectMake(100, 400, 50, 50)]; //平鋪填充 CGContextDrawImage(context, CGRectMake(100, 500, 80, 80), [img CGImage]);//自由縮放 }
效果看起來笨笨的,哈哈,繼續學習ing