天天看点

iphone 自定义控件

iPhone中自绘实现步骤

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];

}