OGeek|极客世界-中国程序员成长平台

标题: ios - 使用ios中的 block 为 View 设置背景图像? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:32
标题: ios - 使用ios中的 block 为 View 设置背景图像?

当用户点击按钮时,我导航到另一个 View ,并为该 View 设置背景图像。但是图像来自 URL。要转换为 NSData 格式需要一些时间。那么,我如何使用 block 来实现这一点.

我使用了下面的代码,但没有运气..

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self setBackGroundImageView];
});


- (void)setBackGroundImageView {
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:sharedDelegate.fbAppScopeId]];

    dispatch_sync(dispatch_get_main_queue(), ^(void) {            
        if (imageData) {
            UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[self squareImageWithImage:[UIImage imageWithData:imageData] scaledToSize:CGSizeMake(100, 100)]];

            CGFloat ratio = backgroundView.frame.size.width/screenWidth;

            CGRect imageFrame = backgroundView.frame;
            imageFrame.size.width = screenWidth;
            imageFrame.size.height = backgroundView.frame.size.height/ratio;

            if (imageFrame.size.height<screenHeight) {
                ratio = backgroundView.frame.size.height/screenHeight;
                imageFrame.size.height = screenHeight;
                imageFrame.size.width = backgroundView.frame.size.width/ratio;
            }

            backgroundView.frame = imageFrame;
            backgroundView.center = CGPointMake(screenWidth/2, backgroundView.center.y);


            backgroundView.alpha = 0.5;
            [self.view addSubview:backgroundView];
        }
    }
}



Best Answer-推荐答案


您不能在除主线程之外的另一个线程上执行 UI 事件(添加或删除 View )。如果你这样做,那可能行为不端。

如果你还想这样做,在主线程上添加 imageView 并在 block 中设置它的图像。

附:您可以使用 block 预加载(在应用启动时)图像数据,一旦完成,您可以将其用作 imageView.image=preLoadImage;

关于ios - 使用ios中的 block 为 View 设置背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979187/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4