agn*_*aft 0 cocoa 2d objective-c
我正在使用Cocoa为Mac OS X编写一个小桌面游戏.我的实际网格绘制如下:
- (void)drawRect:(NSRect)rect
{
for (int x=0; x < GRIDSIZE; x++) {
for (int y=0; y < GRIDSIZE; y++) {
float ix = x*cellWidth;
float iy = y*cellHeight;
NSColor *color = (x % 2 == y % 2) ? boardColors[0] : boardColors[1];
[color set];
NSRect r = NSMakeRect(ix, iy, cellWidth, cellHeight);
NSBezierPath *path = [NSBezierPath bezierPath];
[path appendBezierPathWithRect:r];
[path fill];
[path stroke];
}
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用,除了我看到瓷砖之间的颜色有些错误.我想这是由于一些抗锯齿或类似的.请参阅下面的屏幕截图(希望您也可以看到相同的问题......其中一些黑色线条与瓷砖重叠):

因此我有这些问题:
更新:
const int GRIDSIZE = 16;
cellWidth = (frame.size.width / GRIDSIZE);
cellHeight = (frame.size.height / GRIDSIZE);
Run Code Online (Sandbox Code Playgroud)
如果你想要清晰的矩形,你需要对齐坐标,使它们与底层像素相匹配.NSView有一个为此目的的方法:- (NSRect)backingAlignedRect:(NSRect)aRect options:(NSAlignmentOptions)options.这是绘制网格的完整示例:
const NSInteger GRIDSIZE = 16;
- (void)drawRect:(NSRect)dirtyRect {
for (NSUInteger x = 0; x < GRIDSIZE; x++) {
for (NSUInteger y = 0; y < GRIDSIZE; y++) {
NSColor *color = (x % 2 == y % 2) ? [NSColor greenColor] : [NSColor redColor];
[color set];
[NSBezierPath fillRect:[self rectOfCellAtColumn:x row:y]];
}
}
}
- (NSRect)rectOfCellAtColumn:(NSUInteger)column row:(NSUInteger)row {
NSRect frame = [self frame];
CGFloat cellWidth = frame.size.width / GRIDSIZE;
CGFloat cellHeight = frame.size.height / GRIDSIZE;
CGFloat x = column * cellWidth;
CGFloat y = row * cellHeight;
NSRect rect = NSMakeRect(x, y, cellWidth, cellHeight);
NSAlignmentOptions alignOpts = NSAlignMinXNearest | NSAlignMinYNearest |
NSAlignMaxXNearest | NSAlignMaxYNearest ;
return [self backingAlignedRect:rect options:alignOpts];
}
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要stroke绘制游戏板.要绘制像素对齐的笔划,您需要记住Cocoa中的坐标实际上指向像素的左下角.对于清晰的线条,您需要将坐标从积分坐标偏移半个像素,以便坐标指向像素的中心.例如,要为网格单元格绘制清晰的边框,您可以执行以下操作:
NSRect rect = NSInsetRect([self rectOfCellAtColumn:column row:row], 0.5, 0.5);
[NSBezierPath strokeRect:rect];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2662 次 |
| 最近记录: |