3

私はこの次のコードを持っています:

@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)の後にコメントされた2行を使用しました。確かに白い背景が描かれていました。黒い背景を削除する方法はありますか? MyImageView を初期化するとき、既に backgroundColor を [UIColor clearColor] に設定しています。

どんなアドバイスでも大歓迎です。ありがとう

4

3 に答える 3

4

背景色を に設定する[UIColor clearColor]とうまくいくはずです。またself.opaque = NO、透明度を有効にするように設定します。

また、正しい初期化子が呼び出されていることも確認する必要があります。たとえば、ビューが XIB ファイルの一部である場合、実装する必要がありinitWithCoder:ますinitWithFrame:

于 2012-06-20T11:34:42.817 に答える
2

私は同じ問題を抱えていました-これは私にとってはうまくいきました(Swiftの例)

    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()
于 2016-03-17T16:36:03.863 に答える
0

とにかくCGContextは逆さまに描画されるので、簡単な方法で使用してください

[self.image drawInRect:CGRectMake(rect)]; 

その代わり。

于 2012-06-20T11:23:38.563 に答える