Iphone UIView drawInRect与UIImage在黑背景中产生结果
我有以下代码:Iphone UIView drawInRect与UIImage在黑背景中产生结果,iphone,objective-c,ios,uiview,uiimage,Iphone,Objective C,Ios,Uiview,Uiimage,我有以下代码: @implementation MyImageView @synthesize image; //image is a UIImage - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } -(void) removeFromSuperview { self.image = ni
@implementation MyImageView
@synthesize image; //image is a UIImage
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void) removeFromSuperview
{
self.image = nil;
[super removeFromSuperview];
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
if (self.image)
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
//the below 2 lines is to prove that the alpha channel of my UIImage is indeed drawn
//CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
//CGContextFillRect(context, rect);
CGContextDrawImage(context, self.bounds, self.image.CGImage);
}
}
@end
当我运行代码时,我意识到视图的背景是黑色的。为了测试我的UIImage是否有问题,我使用了在CGContextClearRect(context,rect)之后注释的两行代码。的确,画了一个白色的背景。我是否需要删除黑色背景?当我初始化MyImageView时,我已经将backgroundColor设置为[UIColor clearColor]
任何建议都将不胜感激。
谢谢您的CGContext将颠倒过来 无论如何,只要走简单的路线,使用
[self.image drawInRect:CGRectMake(rect)];
相反。将背景色设置为
[UIColor clearColor]
应该可以工作。同时设置self.opaque=NO
以启用透明度
您还应该检查是否调用了正确的初始值设定项。例如,如果视图是XIB文件的一部分,则需要实现
initWithCoder:
以及initWithFrame:
等。我也遇到了同样的问题-这对我有效(Swift示例)
你为什么不取消注释这两行呢?当我取消注释这两行时,我的背景将是白色的。我需要图像的alpha与背景融合哦,好的,你是现在我知道了,这是我的原始代码。但效果并不理想。奇怪的是,我现在的代码并没有颠倒过来…谢谢。我想我已经定好了。事实证明,我并不是为了我的测试用例而这样做的。一个假警报,谢谢你的建议。你在哪里设置背景。我在属性字符串中使用图像,而不是UIImageView
var backgroundImage = UIImage() //background image - size = 100x100
var frontImage = UIImage() //smaller image to be drawn in the middle
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), false, 0.0) //false here indicates transparent
var context = UIGraphicsGetCurrentContext()!
UIGraphicsPushContext(context)
backgroundImage.drawInRect(CGRectMake(0, 0, 100, 100))
frontImage.drawInRect(CGRectMake((100 - frontImage.size.width) / 2, (diameter - frontImage.size.height) / 2, frontImage.size.width, frontImage.size.height))
UIGraphicsPopContext()
var outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()