如何在uiimageview的某个区域添加alpha

时间:2012-10-31 03:39:41

标签: ios xcode uiimageview uiimage ios6

是否可以在同一图像中的区域上添加alpha属性? 例如

square without alpha

square with alpha

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是将图像分开并将alpha保存为png的一部分,然后将图像视图组织为彼此齐平。

否则,我在常规视图中编写了这个快速代码,它对图像做了同样的事情(我对Core Graphics相对较新,所以我确信有更好的方法可以做到这一点 - 同样,我的例子是图像是并排):

-(void) drawRect {

    // GET THE CONTEXT, THEN FLIP THE COORDS (my view is 189 ponts tall)

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform flip = CGAffineTransformMake(1, 0, 0, -1, 0, 189);
    CGContextConcatCTM(context, flip);

    // GET THE IMAGE REF

    UIImage *targetImage = [UIImage imageNamed:@"test.jpg"];
    CGImageRef imageRef = targetImage.CGImage;

    // SET THE COORDS

    CGRect imageCoords = CGRectMake(0, 0, 116, 189);
    CGRect imageCoordsTwo = CGRectMake(116, 0, 117, 189);

    // CUT UP THE IMAGE INTO TWO IMAGES

    CGImageRef firstImage = CGImageCreateWithImageInRect(imageRef, imageCoords);
    CGImageRef secondImage = CGImageCreateWithImageInRect(imageRef, imageCoordsTwo);

    // DRAW FIRST IMAGE, SAVE THE STATE, THEN SET THE TRANSPARENCY AMOUNT

    CGContextDrawImage(context, imageCoords, firstImage);
    CGContextSaveGState(context);
    CGContextSetAlpha(context, .4f);

    // DRAW SECOND IMAGE, RESTORE THE STATE

    CGContextDrawImage(context, imageCoordsTwo, secondImage);
    CGContextRestoreGState(context);

    // TIDY UP

    CGImageRelease(firstImage);
    CGImageRelease(secondImage);

}