如何向UIImage或UIImageView或UIView添加外部光晕

Jab*_*Jab 9 iphone cocoa-touch core-graphics uiimageview uiimage

我想褪色的阴影/外发光添加到UIImage/ UIImageView/ UIView但我不知道Core Graphics的.

编辑: 请帮助!!

小智 8

采用Cirrostratus概述的方法,保留其缓存副本,然后应用变换以在拖动时更改图像的大小和/或位置.

(警告,这不是功能/测试过的代码,但应该让你入门)

-(UIImage*)addGlowToImage:(UIImage*)imageInput;
{
    CGRect newSize = imageInput.bounds;
    CGImageRef theImage = imageInput.CGImage;

    // expand the size to handle the "glow"
    newSize.size.width += 6.0;
    newSize.size.height += 6.0;
    UIGraphicsBeginImageContext(newSize);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextBeginTransparencyLayerWithRect(ctx, newSize, NULL);
    CGContextClearRect(ctx, newSize);

    // you can repeat this process to build glow.
    CGContextDrawImage(ctx, newSize, theImage); 
    CGContextSetAlpha(ctx, 0.2);  

    CGContextEndTransparencyLayer(ctx);

    // draw the original image into the context, offset to be centered;
    CGRect centerRect = inputImage.bounds;
    centerRect.origin.x += 3.0;
    centerRect.origin.y += 3.0;
    CGContextDrawImage(ctx, centerRect, theImage);

    result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的方法缩放时你会做类似的事情:

// assumes UIImage *cachedImage = [self addGlowToImage:origImage]; has been called already.
// assumes ivars for scale exists

    CGRect newRect = cachedImage.bounds;
    newRect.size.width += scale;
    newRect.size.height += scale;

    [cachedImage drawInRect:newRect];  // image will be scaled to fill destination rectangle.
Run Code Online (Sandbox Code Playgroud)

绝对看看苹果文档.一个很好的起点是Quartz 2D Programming Guide.


小智 5

您可以简单快速地使用它,可以通过uiview,unbutton等使用:

UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(100, 66, 112, 112)];
shadowView.layer.shadowColor = [[UIColor blackColor] CGColor];
shadowView.layer.shadowOpacity = .4;
shadowView.layer.shadowOffset = CGSizeZero;
shadowView.layer.masksToBounds = NO;
Run Code Online (Sandbox Code Playgroud)

如果可以使用收音机,请添加以下内容:

shadowView.layer.shadowRadius = 10.0f;
Run Code Online (Sandbox Code Playgroud)