您的位置:首页 > 其它

iPhone中自绘实现步骤

2012-02-16 17:02 155 查看
1. 继承@interface MyView : UIView {

2. 实现- (void)drawRect:(CGRect)rect

3. 调用addSubView把新生成的view加入进来显示

addSubView[window addSubview:viewController.view];

4.示例代码

- (void)drawRect:(CGRect)rect {

// create the bitmap context

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef context = CGBitmapContextCreate(nil,100,100,8,400, colorSpace,kCGImageAlphaPremultipliedLast);

CFRelease(colorSpace);

// create an arrow image

// set the fill color

CGColorRef fillColor = [[UIColor blackColor] CGColor];

CGContextSetFillColor(context, CGColorGetComponents(fillColor));

CGContextBeginPath(context);

CGContextMoveToPoint(context, 8.0f, 13.0f);

CGContextAddLineToPoint(context, 24.0f, 4.0f);

CGContextAddLineToPoint(context, 24.0f, 22.0f);

CGContextClosePath(context);

CGContextFillPath(context);

CGContextSelectFont ( context, "Arial", 10.f, kCGEncodingMacRoman );

CGContextSetRGBFillColor ( context, 0.0f, 0.0f, 0.f, 1.f );

CGContextSetShouldAntialias ( context, 0 );

CGContextShowText(context, "hh", 2);

// convert the context into a CGImageRef

CGImageRef image = CGBitmapContextCreateImage(context);

CGContextRelease(context);

UIImage* image2 = [UIImage imageWithCGImage:image];

[image2 drawInRect:CGRectMake(0, 0, 120, 160)];

NSString* myStr = @"中文";

UIFont* font = [UIFont systemFontOfSize:12.0];

[myStr drawInRect: CGRectMake(160, 240, 100, 130) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter];

渐变

CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGGradientRef glossGradient;

CGColorSpaceRef rgbColorspace;

size_t num_locations = 3;

CGFloat locations[3] = { 0.0, 0.5, 1.0 };

CGFloat components[12] = { 208/255.0, 208/255.0, 208/255.0, 0.95, // Start color

208/255.0, 208/255.0, 208/255.0, 0.60,

208/255.0, 208/255.0, 208/255.0, 0.10 }; // End color

rgbColorspace = CGColorSpaceCreateDeviceRGB();

glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

CGContextFillRect(currentContext, self.frame);

CGRect currentBounds = self.bounds;

CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);

CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));

CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

CGGradientRelease(glossGradient);

CGColorSpaceRelease(rgbColorspace);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: