场景:比如说,定义一个支持多种格式的控件,包含下拉菜单进行多种选择.由于标准的控件在界面上布局和自己所需的相差很多,所以要对控件进行重绘。
一下是具体实例:
类似于带下拉菜单的文本编辑框。
//// MqjPopUpbutton.m// MqjEditContact//// Created by mac-d on 4/28/15.// copyright (c) 2015 mac-d. All rights reserved.//#import "MqjPopUpbutton.h"@implementation MqjPopUpbutton- (ID)initWithFrame:(NSRect)frame{ self = [super initWithFrame:frame]; if (self) { // Initialization code here. } return self;}-(BOol) isFlipped{ return YES;}- (voID)drawRect:(NSRect)dirtyRect{ // Drawing code here. //[super drawRect:dirtyRect]; [[NScolor colorWithCalibratedRed: 255/255.0 green:255/255.0 blue:255/255.0 Alpha:1] setFill]; NSRectFill(dirtyRect); Nsstring *path =[[NSBundle mainBundle] pathForResource:@"down" ofType:@"png"]; NSImage *image =[[NSImage alloc] initWithContentsOffile:path]; NSRect rect =NSZeroRect; rect.size = [image size]; NSPoint p = dirtyRect.origin; p.x +=dirtyRect.size.wIDth-image.size.wIDth-4; p.y +=(dirtyRect.size.height-image.size.height)/2; [image drawInRect:NSMakeRect(p.x,p.y,image.size.wIDth,image.size.height) fromrect:rect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil]; //画横线 NSBezIErPath *line = [NSBezIErPath bezIErPath]; [line setlinewidth:1]; [[NScolor colorWithCalibratedRed: 147/255.0 green:147/255.0 blue:147/255.0 Alpha:0.5] setstroke]; NSPoint endPoint = dirtyRect.origin; endPoint.x += dirtyRect.size.wIDth; [line movetoPoint:dirtyRect.origin]; [line linetoPoint:endPoint]; [line stroke]; [line movetoPoint:NSMakePoint(dirtyRect.origin.x,dirtyRect.origin.y+dirtyRect.size.height)]; [line linetoPoint:NSMakePoint(endPoint.x,dirtyRect.origin.y+dirtyRect.size.height)]; [line stroke]; //画竖线 [line movetoPoint:dirtyRect.origin]; [line linetoPoint:NSMakePoint(dirtyRect.origin.x,dirtyRect.origin.y+dirtyRect.size.height)]; [line stroke]; [line movetoPoint:endPoint]; [line linetoPoint:NSMakePoint(endPoint.x,dirtyRect.origin.y+dirtyRect.size.height)]; [line stroke]; //对选中的item设置勾选 NSArray *array = [super itemArray]; for(NSMenuItem *item in array) { if (item == [self selectedItem]) { [item setState:NSOnState]; } else { [item setState:NSOffState]; } } Nsstring *Title =[[super selectedItem] Title]; if (Title == nil) { Title = @""; } NSLog(@"Title:%@",Title); //获取字符串的宽度和高度 NSSize TitleSize = [Title sizeWithAttributes:[NSDictionary dictionaryWithObject:[self Font] forKey:NSFontAttributename]]; CGfloat TitleY = dirtyRect.origin.y + (dirtyRect.size.height - TitleSize.height)/2; NSRect rectTitle = dirtyRect; rectTitle.origin = NSMakePoint(10,TitleY); rectTitle.size.height = TitleSize.height; [Title drawInRect:rectTitle withAttributes:nil];}@end
在MainMenu.xib布局一个NSPopUpbutton,class:改为如图所示。
运行结果:
总结以上是内存溢出为你收集整理的[Cocoa]_[初级]_[NSPopUpButton重绘实例]全部内容,希望文章能够帮你解决[Cocoa]_[初级]_[NSPopUpButton重绘实例]所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)