CALayer未显示 [英] CALayer not displaying
问题描述
所以这是我第一次尝试使用CALayer.构建成功,并且没有报告的错误,因此我认为我必须做的事情显然是错误的.但是该图层根本不显示.
So this is my first ever attempt at using a CALayer. Build is successful and no reported bugs, so I assume I must be doing something obviously wrong. But the layer does not display at all.
- (void)viewDidLoad
{
// Get Reliant Magenta in amazingly verbose manner
CGColorSpaceRef rgbaColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat reliantMagentaValues[4] = {(208/255),(27/255),(124/255),0.3f};
CGColorRef reliantMagenta = CGColorCreate(rgbaColorSpace, reliantMagentaValues);
CALayer *reliantCanvasLayer = [CALayer layer];
reliantCanvasLayer.backgroundColor = reliantMagenta;
reliantCanvasLayer.frame = CGRectMake(0, 0, 640, 960);
[super viewDidLoad];
[[[self view] layer] addSublayer:reliantCanvasLayer];
CGColorRelease(reliantMagenta);
}
我得到了一整张洋红色的图片,而不是一整页的洋红色.我如何弄乱这么简单的东西?
Instead of a full page of magenta, I get back an empty view of grey. How am I messing up something this simple?
更新
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Reliant Magenta in amazingly verbose manner
CGColorSpaceRef rgbaColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat reliantMagentaValues[4] = {(208/255),(27/255),(124/255),0.3f};
CGColorRef reliantMagenta = CGColorCreate(rgbaColorSpace, reliantMagentaValues);
[[self view] layer].backgroundColor = reliantMagenta;
CGColorRelease(reliantMagenta);
}
相同的问题,但是视图现在是黑色的,并且不显示在情节提要中添加的元素
same problem, but view is now black and not displaying elements added in the storyboard
推荐答案
一个问题(可能是唯一的问题)是您要创建具有全部零个成分的颜色.当您说 208/255
时,编译器将使用整数执行除法运算并除去余数,因此 208/255
为0.您需要在浮点数中进行除法: 208.0f/255.0f
.
One problem (possibly the only problem) is that you're creating your color with all zero components. When you say 208/255
, the compiler performs the division using integers and drops the remainder, so 208/255
is 0. You need to divide in floating point: 208.0f / 255.0f
.
使用 UIColor
代替自己设置 CGColorSpace
和 CGColor
也容易得多.试试这个:
It's also much easier to use a UIColor
instead of setting up the CGColorSpace
and the CGColor
yourself. Try this:
- (void)viewDidLoad {
[super viewDidLoad];
UIColor *reliantMagenta = [UIColor colorWithRed:208.0f / 255.0f
green:27.0f / 255.0f blue:124.0f / 255.0f alpha:0.3f];
CALayer *magentaLayer = [CALayer layer];
magentaLayer.frame = CGRectMake(0, 0, 640, 960);
magentaLayer.backgroundColor = reliantMagenta.CGColor;
[self.view.layer addSublayer:magentaLayer];
}
这篇关于CALayer未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!