天天看點

【COCOA(MAC) APPLICATION 開發系列之三】自定義NSVIEW并繪制一些常見的圖形及字元串;

不多說,比較簡單,直接給出源碼,大家作為參考吧。

對于cocoa application 話說回來比較easy,如果之前你接觸過ios 的ib的話 ,基本上沒什麼可說的,上手很快;

是以對于cocoa application 不會太快的更新,接着himi将對之前做的動編徹底的更新一版;後期有時間将繼續更新此系列;

1

  言歸正傳,對于自定義nsview上一篇已經介紹了,而且本篇主要繼續深入nsview的drawrect進行繼續研究,示例代碼如下,比較容易了解,而且都已備注的很清楚;

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

//

//  hview.m

//  created by himi on 12-6-7.

//  copyright (c) 2012年 himi. all rights reserved.

#import "hview.h"

@implementation hview

- (id)initwithframe:(nsrect)frame

{

    self = [super initwithframe:frame];

    if (self) {

        // initialization code here.

    }

    return self;

}

- (void)drawrect:(nsrect)dirtyrect

    //-----------擷取整個myview尺寸------------

    nsrect screen = [self bounds];

    int sw = screen.size.width;

    int sh = screen.size.height;

    //-----------設定整個myview的顔色------------

    [[nscolor graycolor] set];

    //-----------填充整個myview---------------

    nsrectfill(screen);

    //-----------繪制字元串---------------

    nsstring * strh= @"基礎繪制   --by himi";

    //--繪制不帶屬性字元串

    [strh drawatpoint:nsmakepoint(sh*0.5, sh-30) withattributes:null];

40

41

42

43

44

45

46

47

    //--繪制帶屬性字元串

    nsmutabledictionary *md = [nsmutabledictionary dictionary];

    [md setobject:[nsfont fontwithname:@"times" size:20] forkey:nsfontattributename];

    [strh drawatpoint:nsmakepoint(sh*0.5, sh-70) withattributes:md];

    //--------繪制矩形----

    nsrect rect1 = nsmakerect(sh*0.5, sh-100, 30, 20);

    nsrect rect2 = nsmakerect(sh*0.5, sh-130, 30, 20);

    //填充矩形

    [nsbezierpath fillrect:rect1];

    //繪制矩形

    [nsbezierpath strokerect:rect2];

    //--------繪制線條(十字線)----

    [[nscolor greencolor] set];

    nspoint  bm =nsmakepoint(sw*0.5, 0);

    nspoint  top =nsmakepoint(sw*0.5, sh);

    nspoint  lf =nsmakepoint(0, sh*0.5);

    nspoint  rt =nsmakepoint(sw, sh*0.5);

    [nsbezierpath strokelinefrompoint:bm topoint:top];

    [nsbezierpath strokelinefrompoint:lf topoint:rt];

    //-------繪制橢圓

    [[nscolor redcolor] set];

    [[nsbezierpath bezierpathwithovalinrect:screen] stroke];

    [self setneedsdisplay:yes];// 強制繪畫

//【備注】

//    cgcontextref ref = [[nsgraphicscontext currentcontext] graphicsport];// 擷取畫布

//    cgcontextflush(ref);//重新整理畫布

-(void) mousedragged:(nsevent *)theevent{

    nspoint mp = [self convertpoint:[theevent locationinwindow] fromview:nil];// 滑鼠新坐标

    nslog(@"mousedragged~%f,%f",mp.x,mp.y);

-(void) mouseup:(nsevent *)theevent{

    nslog(@"mouseup");

-(void) mousedown:(nsevent *)theevent{

    nslog(@"mousedown");

@end

 注意的是:備注 這兩行代碼是直接通過擷取畫布,更新畫布進行繪制,其中繪制代碼省略,比較容易,這裡起個頭,推薦使用此種方式繪制;對于做遊戲的我們,對于畫布重新整理畫布我想是再熟悉不過了!

運作截圖:

【COCOA(MAC) APPLICATION 開發系列之三】自定義NSVIEW并繪制一些常見的圖形及字元串;

<a href="http://www.himigame.com/wp-content/uploads/2012/06/13.png"></a>