简体   繁体   English

UIView未在drawRect中设置背景色

[英]UIView not setting background color in drawRect

I created a class that subclasses UIView. 我创建了一个类来继承UIView。 In the drawRect, I have what should be drawing a orange colored rectangle. 在drawRect中,我应该绘制橙色矩形。 Yet it shows up as black. 但它显示为黑色。

In my custom class: 在我的自定义课程中:

#import "testRect.h"

@implementation testRect

- (id)initWithFrame:(CGRect)frame
{
     self = [super initWithFrame:frame];
     if (self) {

     }
     return self;
}


- (void)drawRect:(CGRect)rect
{
   //// Color Declarations
   UIColor* strokeColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 1];
   UIColor* fillColor2 = [UIColor colorWithRed: 0.886 green: 0.59 blue: 0 alpha: 1];

   //// Rectangle Drawing
   UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(26.5, 171.5, 265, 139)];
   [fillColor2 setFill];
   [rectanglePath fill];
   [strokeColor setStroke];
   rectanglePath.lineWidth = 1;
   [rectanglePath stroke];
}

And my viewcontroller 还有我的视图控制器

#import "ViewController.h"
#import "testRect.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    testRect *test = [[testRect alloc] initWithFrame:CGRectMake(10, 10, 265, 139)];
    [self.view addSubview:test];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

The CGRect used in your drawRect: method is incorrect. drawRect:方法中使用的CGRect不正确。 You want a CGRect that is relative to the view. 您需要相对于视图的CGRect This means the origin will be 0,0. 这意味着原点将为0,0。 Also, the rect should be calculated at runtime based on the view's bounds. 另外,应该在运行时根据视图的边界计算rect。 Do not hardcode it in drawRect: . 不要在drawRect:对其进行硬编码。 This will make the code work properly regardless of what frame is used to create the view. 无论使用什么框架创建视图,这都将使代码正常工作。

The rect you use now (in drawRect: has a y-origin of 171.5 but the view's height is only 139. So all of the drawing you do is outside of the view. That is why it appears black. 您现在使用的矩形(在drawRect: y坐标为171.5,但是视图的高度仅为139。因此,您所做的所有绘图都在视图外部。这就是为什么它显示为黑色的原因。

You probably want: 您可能想要:

CGRect bounds = self.bounds;
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect:bounds];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM