2014-09-04 90 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

相關問題