2014-09-04 46 views
0

起初:否的CGRect不是空的(我硬是找遍了整个网络,并得到了解每一个可能的方式来解决它,但它似乎我没有成功迄今)CGContextAddPath:无效的情况下为0x0

RqButton.h

#import <UIKit/UIKit.h> 

@interface RqButton : UIButton 
@property (nonatomic) int c; 
@property (nonatomic) float r; 
@property (nonatomic) float g; 
@property (nonatomic) CGRect frame; 

- (id)initWithFrame:(CGRect)frame c:(int)c; 
@end 

RqButton.m

#import "RqButton.h" 
#import <QuartzCore/QuartzCore.h> 

@implementation RqButton 

+ (RqButton *)buttonWithType:(UIButtonType)type 
{return [super buttonWithType:UIButtonTypeCustom];} 


- (id)initWithFrame:(CGRect)frame c:(int)c 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { self.r=c%16; 
     self.g=c/16; 

     [self drawRect:frame]; 
    } 
    return self; 
} 


- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 

    float width = CGRectGetWidth(rect); 
    float height = CGRectGetHeight(rect); 

    UIColor *borderColor = [UIColor colorWithRed:0.05f green:0.05f blue:0.05f alpha:1.00f]; 
    NSLog(@"%f",width); 

    CGFloat BGLocations[2] = { 0.0, 1.0 }; 
    CGFloat BgComponents[8] = { self.r*0.33f, self.g*0.33f, 0.0f , 1.0, 
     0.00, 0.00, 0.00, 1.0 }; 
    CGColorSpaceRef BgRGBColorspace = CGColorSpaceCreateDeviceRGB(); 
    CGGradientRef bgRadialGradient = CGGradientCreateWithColorComponents(BgRGBColorspace, BgComponents, BGLocations, 2); 

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, width, height) cornerRadius: 5]; 
    [roundedRectanglePath addClip]; 

    CGPoint startBg = CGPointMake (width*0.5, height*0.5); 
    CGFloat endRadius= 32; 

    CGContextDrawRadialGradient(ctx, bgRadialGradient, startBg, 0, startBg, endRadius, kCGGradientDrawsAfterEndLocation); 
    CGColorSpaceRelease(BgRGBColorspace); 
    CGGradientRelease(bgRadialGradient); 

    [borderColor setStroke]; 
    roundedRectanglePath.lineWidth = 2; 
    [roundedRectanglePath stroke]; 

} 

@end 

调用这样

我不能忽略错误,因为我的应用程序完全冻结了一些时间。我需要做所有这些来定制我的按钮的外观。通过.xib将该类应用于按钮可以很好地工作。

Error>: CGContextAddPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context 

被许多CG方法来; CGContextDrawRadialGradient:clip; CGContextSetStrokeColorWithColor:CGContextSaveGState:CGContextSetLineWidth:[...]

感谢很多提前

回答

0

你不能叫自己的drawRect这样。操作系统在绘制时调用drawRect方法,并且只有在它为您的类设置环境后才能绘制。这就是为什么会出现故障。 如果您想强制平局发生,请调用[self setNeedsDisplay]。

+0

它发生在一个按钮单击,如果我通过“原始”initWithFrame,一切工作正常。正当我必须设置我自己的initWithFrame以将参数传递给类时,所有内容都会中断。 我应该在哪里放[self setNeedsDisplay]; ?我试过了,但并没有让它更好。 – user2875404 2014-09-04 21:54:06

+0

你没有提供足够的代码来查看还在发生什么(例如,没有响应点击调用的代码),但是你不应该从你的init方法调用drawRect,因为这肯定会导致你所看到的上下文错误。你也不应该声明一个名为“frame”的属性,因为该类已经有一个(从UIButton> UIControl> UIView继承)。 – w0mbat 2014-09-05 04:07:31

相关问题