宽容他人,放过自己。

页面的实时刷新

Posted on By anchoriteFili

[self.view setNeedsDisplay];可以实现一个View中的数据重新加载

由于view的drawRect方法不能被外界直接调用,所以,而setNeedsDisplay可以间接的调用drawRecr方法,因此,setNeedsDisplay能够实现view中的数据刷新

#import "RoundImageViewController.h"

#define PHOTO_HEIGHT 150

@interface RoundImageViewController () {
    float changeValue;
}

@end

@implementation RoundImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //自定义图层
    CALayer *layer = [[CALayer alloc] init];
    layer.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    layer.anchorPoint = CGPointMake(0, 0);
    layer.position = CGPointMake(0, 0);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = PHOTO_HEIGHT/2;
    /**
     注意:仅仅设置圆角,对于图形而言可以正常显示,但是对于图层中绘制的图片无法正确显示
          如果想要正确显示则必须设置masksToBounds=YES,剪切字图层
     */
    layer.masksToBounds = YES;
    /**
     阴影效果无法和masksToBounds同事使用,因为masksToBounds的目的就是剪切外边框
     而阴影效果刚好在外边框
     */
//    layer.shadowColor = [UIColor grayColor].CGColor;
//    layer.shadowOffset = CGSizeMake(2, 2);
//    layer.shadowOpacity = 1;
    
    //设置边框
    layer.borderColor = [UIColor whiteColor].CGColor;
    layer.borderWidth = 2;
    
    //设置图层代理
    layer.delegate = self;
    //添加图层到根图层
    [self.view.layer addSublayer:layer];
    
#pragma mark 定时器执行方法
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeLayer) userInfo:nil repeats:YES];
    
    //调用图层setNeedDisplay,否则代理方法不会被调用
    [layer setNeedsDisplay];
}

- (void)changeLayer {
    //调用图层setNeedDisplay,否则代理方法不会被调用
    
    CALayer *layer = self.view.layer.sublayers[0];
    [layer setNeedsDisplay];
}

#pragma mark 绘制图形、图像到图层,注意参数中的ctx是图层的图形上下文,其中绘图位置也是相对图层而言的
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    
    /**
     CALayer的坐标和几何图标是一致的,和手机屏幕的是不一样的
     */
    changeValue += 0.1;
    if (changeValue >= 0) {
        changeValue = -1.0;
    }
    
    NSLog(@"changeValue ======= %f",changeValue);
    
    CGContextSaveGState(ctx);
    
    //图形上下文变形,解决图片倒位的问题
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -PHOTO_HEIGHT);
    
    UIImage *image = [UIImage imageNamed:@"test"];
    //注意这个位置是相对于图层而言的不是屏幕
    CGContextDrawImage(ctx, CGRectMake(60, -180, PHOTO_HEIGHT, PHOTO_HEIGHT), image.CGImage);
    CGContextRestoreGState(ctx);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end