【iOS開發-圖層】自訂圖層的兩種方式

來源:互聯網
上載者:User

標籤:

想要自訂圖層,只需要構建一個類繼承CALayer方法

如果讓自訂圖層初始化上面就有畫好的圖形,有兩種辦法

重寫drawInContext方法

自訂的圖層下面的方法,然後必須自訂的圖層對象顯示調用
[layer setNeedsDisplay]然後才會調用這個方法;

自定圖層檔案

- (void)drawInContext:(CGContextRef)ctx {    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);//設定紅色    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50));//畫圓    CGContextFillPath(ctx);}

控制器檔案

 TestLayer *layer = [TestLayer layer];    layer.bounds = CGRectMake(0, 0, 100, 100);    layer.position = CGPointMake(100, 100);    layer.anchorPoint = CGPointMake(0, 0);    layer.backgroundColor = [UIColor blueColor].CGColor;    layer.cornerRadius = 10;    [layer setNeedsDisplay];//必須要顯示調用這個方法,才會調用上面的那個方法    [self.view.layer addSublayer:layer];
使用代理

首先代理控制器不需要遵循協議,因為這個協議是一個分類,所有的NSObject都實現了

控制器實現代理的方法

#pragma marks -實現代理的方法- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {    CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50));    CGContextFillPath(ctx);}

調用

TestLayer *layer = [TestLayer layer];layer.bounds = CGRectMake(0, 0, 100, 100);layer.position = CGPointMake(100, 100);layer.anchorPoint = CGPointMake(0, 0);layer.backgroundColor = [UIColor blueColor].CGColor;layer.cornerRadius = 10;layer.delegate = self;[layer setNeedsDisplay];//必須顯示調用,不然也不會調用代理的方法[self.view.layer addSublayer:layer];

【iOS開發-圖層】自訂圖層的兩種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.