我正在使用CGContext函数绘制的CGImage创建精灵。我还有一个作为菜单实现的换色机制。但即使我清除了上下文并改变了颜色,用于绘图的颜色仍然保持不变。有没有人有什么问题?
CGContextSaveGState(UIGraphicsGetCurrentContext());
UIGraphicsBeginImageContext(CGSizeMake(40, 40));
if ([color isEqualToString:@"black"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,0, 1);
}
else if ([color isEqualToString:@"red"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0,0,0, 1);
}
else if ([color isEqualToString:@"green"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,1.0,0, 1);
}
else if ([color isEqualToString:@"blue"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,1.0, 1);
}
CGRect rect1 = CGRectMake(0,0,40,40);
CGContextAddEllipseInRect(UIGraphicsGetCurrentContext(),rect1);
CGContextFillPath(UIGraphicsGetCurrentContext());
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGContextFlush(UIGraphicsGetCurrentContext()) ;
CGContextRestoreGState(UIGraphicsGetCurrentContext());
CCSprite *newSprite = [CCSprite spriteWithCGImage:[myImage CGImage] key:@"blackCircle"];
[itemsArray addObject:newSprite];
[newSprite setPosition:point];
[self addChild:newSprite];
答案 0 :(得分:0)
你确定你的颜色变量是否被设置,并且它是正确的字符串编码来传递isEqualToString测试? (即你确定你实际上是在设置代码来设置颜色)。
我将上面的代码复制到视图控制器的viewDidLoad方法中,直到从上下文创建图像,然后将图像添加到视图的imageview子视图中,颜色就出现了。
这是我在视图控制器的viewDidLoad方法中放入的代码 - 视图最后有一个蓝色圆圈,所以看起来你的代码应该可以工作:
CGContextSaveGState(UIGraphicsGetCurrentContext());
UIGraphicsBeginImageContext(CGSizeMake(40, 40));
NSString *color = @"blue";
if ([color isEqualToString:@"black"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1,0,0, 1);
}
else if ([color isEqualToString:@"red"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0,0,0, 1);
}
else if ([color isEqualToString:@"green"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,1.0,0, 1);
}
else if ([color isEqualToString:@"blue"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,1.0, 1);
}
CGRect rect1 = CGRectMake(0,0,40,40);
CGContextAddEllipseInRect(UIGraphicsGetCurrentContext(),rect1);
CGContextFillPath(UIGraphicsGetCurrentContext());
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGContextFlush(UIGraphicsGetCurrentContext()) ;
CGContextRestoreGState(UIGraphicsGetCurrentContext());
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(30,30,200,200)];
imgV.image = myImage;
[self.view addSubview:imgV];
答案 1 :(得分:0)
您需要添加完整的颜色代码参数,如此...
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0/255,0.0/255,0.0/255, 1.0);