IOS开发-使用UIImageView加载网络图片

使用UIImageView加载网络图片可以分为三步

1.创建UIImageView实例:

  UIImageView *imgview = [[UIImageView alloc] init];
    imgview.frame =CGRectMake((self.view.frame.size.width-100)/2, (self.view.frame.size.height-100)/2, 100, 100);

 

2.下载图片数据:

   NSURL *url = [NSURL URLWithString:@"https://img0.baidu.com/it/u=1752903520,1572100722&fm=253&fmt=auto&app=138&f=JPEG?w=521&h=500"];
    NSData *data = [NSData dataWithContentsOfURL:url];

 

3.从数据生成图片并设置UIImageView的image属性:

 UIImage *image = [UIImage imageWithData:data];
    imgview.image = image;

效果图:

 完整代码:

UIImageView *imgview = [[UIImageView alloc] init];
    imgview.frame =CGRectMake((self.view.frame.size.width-100)/2, (self.view.frame.size.height-100)/2, 100, 100);
    NSURL *url = [NSURL URLWithString:@"https://img0.baidu.com/it/u=1752903520,1572100722&fm=253&fmt=auto&app=138&f=JPEG?w=521&h=500"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    imgview.image = image;
    
     UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imgview.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imgview.bounds.size];

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
        //设置大小
        maskLayer.frame = imgview.bounds;
        //设置图形样子
        maskLayer.path = maskPath.CGPath;
        imgview.layer.mask = maskLayer;
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:imgview];

 

posted @ 2023-07-02 16:32  SadicZhou  阅读(881)  评论(0编辑  收藏  举报