-
Notifications
You must be signed in to change notification settings - Fork 28
/
NSImage-Tile.m
103 lines (85 loc) · 3.4 KB
/
NSImage-Tile.m
1
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// NSImage-Tile.m
// Crimson
//
// Created by jeff on 10/7/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "NSImage-Tile.h"
@implementation NSImage(Tile)
-(NSImage *)subImageWithTileWidth:(CGFloat)tileWidth tileHeight:(CGFloat)tileHeight column:(NSUInteger)column row:(NSUInteger)row
{
if (column >= [self columnsWithTileWidth:tileWidth])
return nil;
if (row >= [self rowsWithTileHeight:tileHeight])
return nil;
NSBitmapImageRep *imageRep = [[[NSBitmapImageRep alloc] initWithCGImage:[self CGImageForProposedRect:NULL context:NULL hints:nil]] autorelease];
int width = [imageRep pixelsWide];
int height = [imageRep pixelsHigh];
int bytesPerPixel = [imageRep bitsPerPixel] / 8;
int theRow = row * tileHeight;
int theCol = column * tileWidth;
int i,x,y;
unsigned char *p1, *p2;
int lastCol;
int outputWidth;
if (theCol + tileWidth > width) // last column, not full size
{
lastCol = width;
outputWidth = (width - theCol);
}
else
{
lastCol = theCol + tileWidth;
outputWidth = tileWidth;
}
int lastRow, outputHeight;
if (theRow + tileHeight > height)
{
lastRow = height;
outputHeight = (height - theRow);
}
else
{
lastRow = theRow + tileHeight;
outputHeight = tileHeight;
}
NSImage *ret = [[NSImage alloc] initWithSize:NSMakeSize(outputWidth,outputHeight)];
NSBitmapImageRep *retRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:outputWidth
pixelsHigh:outputHeight
bitsPerSample:[imageRep bitsPerSample]
samplesPerPixel:[imageRep samplesPerPixel]
hasAlpha:[imageRep hasAlpha]
isPlanar:[imageRep isPlanar]
colorSpaceName:[imageRep colorSpaceName]
bitmapFormat:[imageRep bitmapFormat]
bytesPerRow:[imageRep bytesPerRow]
bitsPerPixel:[imageRep bitsPerPixel]];
unsigned char *srcData = [imageRep bitmapData];
unsigned char *destData = [retRep bitmapData];
for (x = theCol; x < lastCol; x++)
{
for (y = theRow; y < lastRow; y++)
{
p1 = srcData + bytesPerPixel * (y * width + x);
p2 = destData + bytesPerPixel * ((y - theRow) * width + (x - theCol));
for (i = 0; i < bytesPerPixel; i++)
p2[i] = p1[i];
}
}
[ret addRepresentation:retRep];
[retRep release];
return [ret autorelease];
}
-(NSUInteger)columnsWithTileWidth:(CGFloat)tileWidth
{
CGFloat columns = [self size].width / tileWidth;
return (NSUInteger) ceilf(columns);
}
-(NSUInteger)rowsWithTileHeight:(CGFloat)tileHeight
{
CGFloat rows = [self size].height / tileHeight;
return (NSUInteger) ceilf(rows);
}
@end