这两天略废,前两天有哥们儿,让我打印一个棱形,手写真的费劲啊。
于是乎,我用了几乎一下午,用代码画了出来。
先晒一下,结果
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
- (void)draw
{
NSInteger maxStarCount = 10;
NSInteger width = maxStarCount*2 -1;
NSInteger height = width;
NSInteger middleIndex = maxStarCount - 1;
NSMutableArray *currentRowStarIndexArray = [NSMutableArrayarray];
NSInteger currentRowStarCount ;
//上半个棱形
for (NSInteger row =0; row < maxStarCount; row ++) {
currentRowStarCount = row + 1;
currentRowStarIndexArray = [self currentRowStarIndexArray:currentRowStarCount middleIndex:middleIndexrow:row];
[self printCurrentRowStarIndexArray:currentRowStarIndexArraywidth:width row:row];
printf("\n");
}
//下半个棱形
for (NSInteger row = maxStarCount; row < height; row ++) {
currentRowStarCount = maxStarCount - (row - maxStarCount + 1);
currentRowStarIndexArray = [self currentRowStarIndexArray:currentRowStarCount middleIndex:middleIndexrow:row];
[self printCurrentRowStarIndexArray:currentRowStarIndexArraywidth:width row:row];
printf("\n");
}
}
- (NSMutableArray *)currentRowStarIndexArray:(NSInteger)currentRowStarCount middleIndex:(NSInteger)middleIndex row:(NSInteger)row
{
NSMutableArray *currentRowStarIndexArray = [NSMutableArrayarray];
NSInteger printTimes = ceil((double)currentRowStarCount/(double)2.0f);
for (int step =0; step < printTimes; step++) {
//第一行,奇数行
if (row % 2 == 0) {
if (step == 0) {
[currentRowStarIndexArray addObject:@(middleIndex + step)];
}
else
{
[currentRowStarIndexArray addObject:@(middleIndex +2*step)];
[currentRowStarIndexArray addObject:@(middleIndex -2*step)];
}
}
else
{
if (step == 0) {
[currentRowStarIndexArray addObject:@(middleIndex +1)];
[currentRowStarIndexArray addObject:@(middleIndex -1)];
}
else
{
[currentRowStarIndexArray addObject:@(middleIndex +1 + 2*step)];
[currentRowStarIndexArray addObject:@(middleIndex -1 - 2*step)];
}
}
}
return currentRowStarIndexArray;
}
- (void)printCurrentRowStarIndexArray:(NSMutableArray *)currentRowStarIndexArray width:(NSInteger)width row:(NSInteger)row
{
for (int column =0; column < width; column ++) {
NSPredicate *pred = [NSPredicatepredicateWithFormat:@"SELF = %@",@(column)];
NSArray *resultArray = [currentRowStarIndexArrayfilteredArrayUsingPredicate:pred];
BOOL isStar = [resultArray count] > 0 ? YES:NO;
if (isStar) {
printf("*");
}
else
{
printf(" ");
}
}
}
end
大概的思路是,从中间开始画,如果是奇数行,第一次画一个点,如果是偶数行,第一次画两个点。
因为知道每一行,有几个点,所以可以知道,画了多少次。先实现吧,别的方法再议。
1.先画一个平行四边形,然后旋转,挪移?