起初:没有CGRect不是空的(我在整个网站上搜索并了解了解决它的所有可能方法,但到目前为止我似乎没有成功)
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
像这样调用类
int xz= buttons[x][y].frame.origin.x;
int yz= buttons[x][y].frame.origin.y;
buttons[x][y] = [[RqButton alloc] initWithFrame:CGRectMake(xz, yz, 30, 30) c:(int)51 ];
[buttons[x][y] addTarget:self action:@selector(actionPick:) forControlEvents:UIControlEventTouchDown];
buttons[x][y].tag = tag;
[self.view addSubview:buttons[x][y]];
我不能忽略错误,因为我的应用程序完全冻结了一些时间。我需要做所有这些来自定义按钮的外观。通过.xib将类应用于Button非常合适。
此
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 :(得分:0)
你不能那样自己调用drawRect。操作系统在绘制时调用drawRect方法,并且只有在为类设置环境之后才调用。这就是崩溃的原因。 如果你想尽快强制平局,请调用[self setNeedsDisplay]。