美文网首页
绘图的几种方式

绘图的几种方式

作者: c048e8b8e3d7 | 来源:发表于2017-01-13 16:55 被阅读66次

    一 使用CALayerDelegate来绘图

    @interface ViewController ()<CALayerDelegate>
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(87.5, 80, 200, 100);
        layer.delegate = self;
        [self.view.layer addSublayer:layer];
        //不调用下面的语句,将不会执行CALayerDelegate中的方法
        [layer setNeedsDisplay];
    }
    
    - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
    {
        CGSize size = layer.bounds.size;
        CGMutablePathRef path = CGPathCreateMutable();
        CGContextMoveToPoint(ctx, 0, size.height);
        CGContextAddLineToPoint(ctx, size.width, size.height);
        CGContextAddLineToPoint(ctx, size.width / 2, 0);
        CGContextClosePath(ctx);
        
        UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"star"]];
        CGContextSetFillColorWithColor(ctx, color.CGColor);
        CGContextAddPath(ctx, path);//记得将path添加进来
        CGPathRelease(path);
        CGContextFillPath(ctx);
    }
    

    二 使用UIView的drawRect:方法来绘图

    @interface TestView : UIView
    
    @end
    
    - (void)drawRect:(CGRect)rect 
    {    
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"star"]];
        CGContextSetFillColorWithColor(ctx, color.CGColor);
        CGContextFillEllipseInRect(ctx, rect);
    }
    

    调用

    TestView *testView = [[TestView alloc] initWithFrame:CGRectMake(87.5, 220, 200, 200)];
    testView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:testView];
    

    三 使用UIGraphicsBeginImageContext相关方法来绘图

    - (void)drawAnyWhere
    {
        //下面两句顺序不能颠倒
        //UIGraphicsBeginImageContext(CGSizeMake(200, 100));
        //不能使用上一个方法,因为Retina屏的scale为2或3,而上一个方法的scale是1,会造成图片模糊,0.0表示根据ping'm
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 100), NO, 0.0);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddEllipseInRect(path, NULL, CGRectMake(0, 0, 200, 100));
        CGContextAddPath(ctx, path);
        UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"star"]];
        CGContextSetFillColorWithColor(ctx, color.CGColor);
    
        CGContextFillPath(ctx);
        CGPathRelease(path);
    
        //获取绘制的图像
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(87.5, 470, 200, 100)];
        imageView.image = image;
    
        [self.view addSubview:imageView];
    }
    

    效果

    效果图

    相关文章

      网友评论

          本文标题:绘图的几种方式

          本文链接:https://www.haomeiwen.com/subject/uxcjbttx.html