问题
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