如何为UIImage、UIImageView或UIView添加外发光效果

9

我想在UIImage/UIImageView/UIView上添加一个淡化的阴影/外发光,但是我完全不懂Core Graphics

编辑: 请帮忙!!

3个回答

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;
}

在进行缩放时,您的方法应该做如下处理:
// 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.

一定要看看苹果的文档。一个好的起点是Quartz 2D编程指南


好吧,不完全是我想要的,但我会接受。我想要一个淡入淡出效果。 - Jab
1
你也可以通过改变颜色,将阴影属性用作发光效果。简单易行。 - zekel
1
在2010年提供答案时,它是合适的。如果您不喜欢这种方法,请使用一些新的可用API提供更好的答案。 - Chip Coons
@MarkMolina 我同意Chip Coons的观点。如果你不喜欢这种方法,那么请提供一个更好的答案,而不是批评别人的答案。这样做没有任何帮助。 - fulvio
当然有帮助。它可以警告那些不知情的程序员有关糟糕代码的问题,或许他们可以在那段代码上进行改进。我并不是在挑剔那段代码,很高兴看到人们花费时间研究这些主题,但我只是想说这段代码不够优化。 - Mark Molina

6
你可以使用这个简单快速的方法,它使用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;

如果你可以使用收音机,就添加这个:

shadowView.layer.shadowRadius = 10.0f;

2
作为性能考虑,iPhone OS不支持shadowColor、shadowOffset、shadowOpacity和shadowRadius属性,这些属性在Cocoa中通常可以使用。大多数人会多次复制他们想要发光的形状,每次降低不透明度并将形状偏移一个像素来模拟发光的外观。如果你的发光不需要很大,你几乎看不出区别。

如果视图每秒更新多次,这将占用大量性能。我正在使用“touchesMoved”事件更改大小。 - Jab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接