gpt4 book ai didi

ios - UIView 背景颜色始终为黑色

转载 作者:IT王子 更新时间:2023-10-29 08:04:59 26 4
gpt4 key购买 nike

当我以编程方式将 UIView 添加到 View Controller 时,我无法将背景颜色更改为任何其他颜色,它始终保持黑色。

- (void)drawRect:(CGRect)rect
{
// Drawing code
self.backgroundColor = [UIColor blueColor];

UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}

当我注释掉 drawrect: 并将 self.backgroundColor = [UIColor blueColor]; 添加到初始化程序时,颜色会发生变化:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor blueColor]
}
return self;
}

这是为什么?我需要更改什么?其实我希望背景是透明的。

最佳答案

当您实现 drawRect: 时,这将覆盖 UIView 的任何默认绘图。

您必须将自定义 View 的 opaque 属性设置为 NO 并在呈现路径之前清除上下文:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.opaque = NO;
}
return self;
}

- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);

UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}

https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instp/UIView/opaque

An opaque view is expected to fill its bounds with entirely opaque content—that is, the content should have an alpha value of 1.0. If the view is opaque and either does not fill its bounds or contains wholly or partially transparent content, the results are unpredictable. You should always set the value of this property to NO if the view is fully or partially transparent.

关于ios - UIView 背景颜色始终为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com