2012年9月11日 星期二

繪圖基本實作(一)

實作一個畫圓的繪圖功能
Xcode版本4.4.1

細節說明請看 UIView說明 http://kirenenko-tw.blogspot.tw/2012/06/uiview.html

1. 先開一個專案,同樣用Single View Application的 Template

2. 新增一個draw的Class,繼承自UIView


   

3. 先針對draw.m修改,增加畫圓的程式碼

- (void)drawCircleAtPoint:(CGPoint)p withRadius:(CGFloat)radius inContext:(CGContextRef)context
{
    UIGraphicsPushContext(context);
    CGContextBeginPath(context);
    CGContextAddArc(context, p.x, p.y, radius, 0, 2*M_PI, YES); // 360 degree (0 to 2pi) arc
    CGContextStrokePath(context);
    UIGraphicsPopContext();
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
   
    CGPoint midPoint; // center of our bounds in our coordinate system
    midPoint.x = self.bounds.origin.x + self.bounds.size.width/2;
    midPoint.y = self.bounds.origin.y + self.bounds.size.height/2;
   
    CGFloat size = self.bounds.size.width / 2;
    if (self.bounds.size.height < self.bounds.size.width) 
         size = self.bounds.size.height / 2;
    ///size *= self.scale; // scale is percentage of full view size
   
    CGContextSetLineWidth(context, 5.0);
    [[UIColor blueColor] setStroke];
   
    [self drawCircleAtPoint:midPoint withRadius:size inContext:context]; // head
   
}


4. 修改drawViewController.h

#import <UIKit/UIKit.h>
#import "draw.h"  // 加入 class draw到ViewController

@interface drawViewController : UIViewController

@end

5. 修改drawViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    //增加畫圓形的instance到ViewController
    draw *drawCircle = [[draw alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:drawCircle];
   
    // 設定背景為白色。
    drawCircle.backgroundColor = [UIColor whiteColor];
   
}


6. 執行後結果如下