iPhone光泽图标使用核心graphics

我想知道是否有人知道如何使用CoreGraphics的图像,并添加像你在iOS上看到的光泽效果。 具体来说,我想从网上下载一个图像,并像这样的样式。 我search了高和低,所有我find的是如何在PhotoShop中,而不是在代码中的例子。 任何代码片段或指向资源,可以帮助我将不胜感激。

我浪费了几个小时试图弄清楚这一点后,我自己想出来了…这是我的代码:

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight) { float fw, fh; if (ovalWidth == 0 || ovalHeight == 0) { CGContextAddRect(context, rect); return; } CGContextSaveGState(context); CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect)); CGContextScaleCTM (context, ovalWidth, ovalHeight); fw = CGRectGetWidth (rect) / ovalWidth; fh = CGRectGetHeight (rect) / ovalHeight; CGContextMoveToPoint(context, fw, fh/2); CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); CGContextClosePath(context); CGContextRestoreGState(context); } static void addGlossPath(CGContextRef context, CGRect rect) { CGFloat quarterHeight = CGRectGetMidY(rect) / 2; CGContextSaveGState(context); CGContextBeginPath(context); CGContextMoveToPoint(context, -20, 0); CGContextAddLineToPoint(context, -20, quarterHeight); CGContextAddQuadCurveToPoint(context, CGRectGetMidX(rect), quarterHeight * 3, CGRectGetMaxX(rect) + 20, quarterHeight); CGContextAddLineToPoint(context, CGRectGetMaxX(rect) + 20, 0); CGContextClosePath(context); CGContextRestoreGState(context); } UIImage *applyIconHighlightToImage(UIImage *icon) { UIImage *newImage; CGContextRef context; CGGradientRef glossGradient; CGColorSpaceRef rgbColorspace; CGRect currentBounds = CGRectMake(0, 0, icon.size.width, icon.size.height); CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f); CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)); CGFloat locations[2] = {0.0, 1.0}; CGFloat components[8] = {1.0, 1.0, 1.0, 0.75, 1.0, 1.0, 1.0, 0.2}; UIGraphicsBeginImageContext(icon.size); context = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context); addRoundedRectToPath(context, currentBounds, 10, 10); CGContextClosePath(context); CGContextClip(context); [icon drawInRect:currentBounds]; addGlossPath(context, currentBounds); CGContextClip(context); rgbColorspace = CGColorSpaceCreateDeviceRGB(); glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, 2); CGContextDrawLinearGradient(context, glossGradient, topCenter, midCenter, 0); UIGraphicsPopContext(); newImage = UIGraphicsGetImageFromCurrentImageContext(); CGGradientRelease(glossGradient); CGColorSpaceRelease(rgbColorspace); UIGraphicsEndImageContext(); return newImage; } 

编辑:希望确保我信贷信用到期。 感谢Brad Larson为添加光滑渐变的代码。

我在这里提供了使用Core Graphics绘制光滑渐变的代码。

如果你想要做的只是在你的图像上覆盖一个光泽效果,那么使用CAGradientLayer生成这个效果可能会更高效,正如Mirko在他的回答中所描述的那样。