使用AFNetworking setImageWithURL设置UIImageView圆角:

时间:2013-04-14 19:58:36

标签: ios cocoa-touch calayer afnetworking

这在UIImageView上不使用AFNetworking的类别方法时有效,但我意识到AF可能会覆盖所做的任何事情,因为这发生了异步:

这是我的自定义UITableViewCell(自己是单元格):

NSURL *url = [NSURL URLWithString:video.thumbnail];    
[self.imageView setImageWithURL:url
               placeholderImage:[UIImage imageNamed:@"Logo.png"]];
// not working
CALayer *layer = [self.imageView layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:10.0];

尝试在调用setImageWithURL之前放置它。

这就是我现在所拥有的,而不是四处转弯:

NSURL *url = [NSURL URLWithString:_video.thumbnail];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIImage *placeHolder = [UIImage imageNamed:@"Logo"];
__weak UIImageView *imageView = self.thumbnail;

[self.thumbnail setImageWithURLRequest:request placeholderImage:placeHolder success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

    imageView.image = image;
    // round the edges of the video thumbnail
    CALayer *layer = [imageView layer];
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:8.0];

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"couldn't load image: %@", [error localizedDescription]);
}];

3 个答案:

答案 0 :(得分:5)

NSURLRequest *request = [NSURLRequest requestWithURL:url];
__weak UIImageView *imageView = self.imageView;
[self.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"Logo.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    imageView.image = image;
    CALayer *layer = imageView.layer;
    layer.masksToBounds = YES;
    layer.cornerRadius = 10.0f;
} failure:NULL];

答案 1 :(得分:2)

我从未使用AFNetworking,但我发现有setImageWithURL方法的版本需要“成功”块。尝试使用该版本,并在“成功”块中更新图像视图的图层。

答案 2 :(得分:0)

https://github.com/rs/SDWebImage提供的SDWebImage库包括以下方法:

  • (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)占位符已完成:(SDWebImageCompletedBlock)completedBlock;

以下代码是我正在处理的项目的示例实现,具有相当大的圆角。我在同一个项目中使用了AFNetworking和SDWebImage。

    __weak UIImageView * theImageView = self.imageView;

    [self.imageView setImageWithURL:[NSURL URLWithString:user.imgurl] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        // I only attempt to apply this if an image has been returned.
        if (image) {
            theImageView.image = image;
            CALayer * layer = theImageView.layer;
            layer.masksToBounds = YES;
            layer.cornerRadius = 20.0f;
        }

    }];