我試圖適應蘋果以編程方式繪製一線明星提供了一個示例,代碼如下:如何使用Quartz Core繪製星星?
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, aSize);
for (NSUInteger i=0; i<stars; i++)
{
CGContextSetFillColorWithColor(context, aColor);
CGContextSetStrokeColorWithColor(context, aColor);
float w = item.size.width;
double r = w/2;
double theta = 2 * M_PI * (2.0/5.0); // 144 degrees
CGContextMoveToPoint(context, 0, r);
for (NSUInteger k=1; k<5; k++)
{
float x = r * sin(k * theta);
float y = r * cos(k * theta);
CGContextAddLineToPoint(context, x, y);
}
CGContextClosePath(context);
CGContextFillPath(context);
}
上面的代碼繪製一個完美的明星,但爲1翻轉顯示2.是黑色的,沒有邊界。我想要達到的目的是在同一條線上和給定的風格上畫出許多恆星。我知道我實際上在同一個位置上繪製了相同的路徑5次,並且我以某種方式垂直翻轉了上下文,但經過幾次測試後,我放棄了! (我缺乏必要的數學和幾何技能:P)...你能幫我嗎?
UPDATE:
好,感謝CocoaFu,這是我的重構和工作抽獎工具:
- (void)drawStars:(NSUInteger)count inContext:(CGContextRef)context;
{
// constants
const float w = self.itemSize.width;
const float r = w/2;
const double theta = 2 * M_PI * (2.0/5.0);
const float flip = -1.0f; // flip vertically (default star representation)
// drawing center for the star
float xCenter = r;
for (NSUInteger i=0; i<count; i++)
{
// get star style based on the index
CGContextSetFillColorWithColor(context, [self fillColorForItemAtIndex:i]);
CGContextSetStrokeColorWithColor(context, [self strokeColorForItemAtIndex:i]);
// update position
CGContextMoveToPoint(context, xCenter, r * flip + r);
// draw the necessary star lines
for (NSUInteger k=1; k<5; k++)
{
float x = r * sin(k * theta);
float y = r * cos(k * theta);
CGContextAddLineToPoint(context, x + xCenter, y * flip + r);
}
// update horizontal center for the next star
xCenter += w + self.itemMargin;
// draw current star
CGContextClosePath(context);
CGContextFillPath(context);
CGContextStrokePath(context);
}
}
你是什麼意思倒掛?明星沒有「底」,我錯了嗎?也許你可以張貼一些截圖,你目前得到的和你的期望。 –
星星的底部通常有一個頂點和一個2點。正常明星:http://www.allstarbaseballcamp.com/star_clipart.gif,顛倒(垂直翻轉)明星:http://sunandshield.files.wordpress.com/2010/03/eastern-star.jpg – daveoncode
請參閱https: //calayer.com/core-animation/2016/05/22/cashapelayer-in-depth.html#path – iwasrobbed