IOS UIImageView 显示黑色背景 [英] IOS UIImageView displays with black background
问题描述
所以我有这个缩放UIImages
的函数,我用它来初始化一个带有图像的UIImageView
.我的问题是当显示图像时,它周围总是有一个黑色矩形,尽管图像是背景中完全透明的 .png.
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.
这里是缩放方法以及UIImageView
的初始化:
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];
}
如您所见,我已使用 [image setBackgroundColor:[UIColor clearColor]];
尝试将 UIImageView
的背景颜色设置为清除,但这似乎不起作用.
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.
推荐答案
您所需要做的就是
UIGraphicsBeginImageContextWithOptions( newSize, NO, 0 );
并且比例因子将自动设置,结果图像中未触及的像素将是透明的.
and the scale factor will be set automatically, and the untouched pixels in the resulting image will be transparent.
这篇关于IOS UIImageView 显示黑色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!