【Cocoa(mac) Application 开发系列之三】自定义NSView并绘制一些常见的图形及字符串;
2015-11-18 09:29
621 查看
【Cocoa(mac) Application 开发系列之三】自定义NSView并绘制一些常见的图形及字符串;
对于Cocoa application 话说回来比较easy,如果之前你接触过iOS 的IB的话 ,基本上没什么可说的,上手很快;因此对于Cocoa Application 不会太快的更新,接着Himi将对之前做的动编彻底的更新一版;后期有时间将继续更新此系列;
言归正传,对于自定义NSView上一篇已经介绍了,而且本篇主要继续深入NSView的drawRect进行继续研究,示例代码如下,比较容易理解,而且都已备注的很清楚;
// // 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];
//--绘制带属性字符串 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 开发系列之二】总结一些常用控件以及简单在自定义View上绘制字符串
- 安卓App热补丁动态修复技术介绍
- 浅析iOS应用开发中线程间的通信与线程安全问题
- 自定义View步骤
- unity中实现压缩解压功能
- 【Cocoa(mac) Application 开发系列之一】创建第一个application—计算器
- 在android studio上使用小米真机调试
- android多媒体编程--加载大图片
- IOS程序crash捕获
- unity中实现断点续传功能
- 关于android使用Xutil保存cookie
- iOS 9的 Core Image新滤镜
- App界面交互设计规范
- Android Dev Tools
- iOS 百度统计的使用技巧
- Android之activity的生命周期
- [Android自定义控件] Android自定义控件
- swift之类和结构体
- android学习路径
- Android手势识别器