IOS UIImageView displays with black background

家住魔仙堡 提交于 2019-12-24 08:49:40

问题


So I've got this function that scales UIImages, and I'm using it to initialise a UIImageView with an image. My problem is that the when the image is displayed, it always has a black rectangle around it, despite the image being a .png with full transparency in the background.

Here is the scaling method as well as the initialisation of the UIImageView:

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([[UIScreen mainScreen] scale] == 2.0) {
        UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
    } else {
        UIGraphicsBeginImageContext(newSize);
    }
} else {
    UIGraphicsBeginImageContext(newSize);
}
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

- (void)addMass:(Mass *)mass{
UIImageView *image = [[UIImageView alloc]initWithImage:[self imageWithImage:[UIImage imageNamed:@"circle.png"] scaledToSize:CGSizeMake(mass.mass, mass.mass)]];
[image setBackgroundColor:[[UIColor alloc]initWithRed:0 green:0 blue:0 alpha:1]];
image.center = [mass position];
[image setBackgroundColor:[UIColor clearColor]];
[massImages addObject:image];
[self.view addSubview:image];
}

As you can see I've used [image setBackgroundColor:[UIColor clearColor]]; to try and set the background color of the UIImageView to clear, but this does not seem to be working.


回答1:


All you need to do is

UIGraphicsBeginImageContextWithOptions( newSize, NO, 0 );

and the scale factor will be set automatically, and the untouched pixels in the resulting image will be transparent.



来源:https://stackoverflow.com/questions/23354975/ios-uiimageview-displays-with-black-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!