[英]UIView not setting background color in drawRect
我創建了一個類來繼承UIView。 在drawRect中,我應該繪制橙色矩形。 但它顯示為黑色。
在我的自定義課程中:
#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];
}
還有我的視圖控制器
#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
在drawRect:
方法中使用的CGRect
不正確。 您需要相對於視圖的CGRect
。 這意味着原點將為0,0。 另外,應該在運行時根據視圖的邊界計算rect。 不要在drawRect:
對其進行硬編碼。 無論使用什么框架創建視圖,這都將使代碼正常工作。
您現在使用的矩形(在drawRect:
y坐標為171.5,但是視圖的高度僅為139。因此,您所做的所有繪圖都在視圖外部。這就是為什么它顯示為黑色的原因。
您可能想要:
CGRect bounds = self.bounds;
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect:bounds];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.