总结一些Cocoa画图的常用代码。
一、画点
points(NSPoint)
同直角坐标系一样原点在左下角
结构:
typedef struct _NSPoint{
float x;
float y;
}NSPoint;
使用:
NSPoint thePoint; //定义
thePoint=NSMakePoint(0,0); //初始化
二、画长方形
两种初始化的方式
结构1:
typedef struct _NSRect{
NSPoint origin;
NSSize size;
}NSRect;
结构2:
typedef struct _NSSize{
float width;
float height;
}NSSize;
使用:
NSRect theRect1; //定义
theRect1=NSMakeRect(0,0,100,100); //初始化
NSRect theRect2; //定义
theRect2 = NSMakeRect(20,10); //初始化
三、选颜色
两种初始化方式
1:简单方式,用系统已提供的颜色名称
NSColor *aColor;
aColor=[NSColor blackColor]; //黑色
//以下是其它颜色
blackColor 黑色
blueColor 蓝色
brownColor 褐色
cyanColor 青色
DarkGrayColor 深灰色
grayColor 灰色
greenColor 绿色
lightGrayColor 浅灰色
magentaColor 紫红
orangeColor 橙色
purpleColor 紫色
redColor 红色
whiteColor 白色
yellowColor 黄色
2:自己新建颜色
//参数值为0-1,颜色表示[(num +1)/256],alpha表不透明度
NSColor=theColor;//black
theColor=[NSColor colorWithDeviceRed:(float)0.0,
green:(float)0.0 blue:(float)0.0 alpha:(float)1.0];
[theColor set];//设置画笔
四、用线和图形绘画
利用点成线,线成面的原理
画一个矩形
//画一个矩形
NSRect theRect;
theRect=NSMakeRect(0,0,100,100);
NSBezierPath *thePath;
thePath=[NSBezierPath bezierPathWithRect:theRect];
//bezierPathWithOvalInRect 画椭圆
//用颜色填充矩形
NSColor *theColor=[NSColor blackColor];
[theColor set];
[thePath fill];
//画一条线
//画一条线就相当于在一条线周围描个框,并填充它
//在上面已填充的矩形周围描框,需要的操作同上相反
theColor=[NSColor blackColor];
[theColor set];
[thePath setLineWidth:5];
[thePath stroke];
//画任意图形
//用多个点连成线然后填充构成图形,有起始点,其它点以起始点为相对坐标,移动图形时仅需要改变起始点坐标
//+X:X右边; -X:X左边; +Y:Y上边; -Y:Y下边
NSBezierPath *stopSign=[NSBezierPath bezierPath];
NSPoint pt1,pt2,pt3,pt4,pt5;//五边形
pt1=NSMakePoint(300,300);
pt2=NSMakePoint(400,300);
pt3=NSMakePoint(450,200);
pt4=NSMakePoint(350,100);
pt5=NSMakePoint(250,200);
[stopSign moveToPoint:pt1];
[stopSign relativeLineToPoint:pt2];
[stopSign relativeLineToPoint:pt3];
[stopSign relativeLineToPoint:pt4];
[stopSign relativeLineToPoint:pt5];
[stopSign closePath];
[[NSColor redColor] set];
[stopSign fill];
[[NSColor whiteColor]set];
[stopSign setLineWide:5];
[stopSign stroke];
五、画文字
NSMutableAttributedString *s = [[NSMutableAttributedString alloc] initWithString:@"Big Nerd Ranch"];
//字体大小
[s addAttribute:NSFontAttributeName value:[NSFont userFontOfSize:22] range:NSMakeRange(0,14)];
//给字体加下划线
[s addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:NSMakeRange(0,14)];
//字体颜色
[s addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:NSMakeRange(0,14)];
[s drawInRect:[self bounds]];
运行结果:
六、显示图片
NSPoint theImagePos=NSMakePoint(0,0)
NSImage * theImage=[NSImage imageNamed:@"mypic.jpg"];
[theImage dissolveToPoint:theImagePos fraction:(1.0)];
//fraction的值表示图片显示的不透明度:1表不透明