不多说,比较简单,直接给出源码,大家作为参考吧。
对于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
注意的是:备注 这两行代码是直接通过获取画布,更新画布进行绘制,其中绘制代码省略,比较容易,这里起个头,推荐使用此种方式绘制;对于做游戏的我们,对于画布刷新画布我想是再熟悉不过了!
运行截图:

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