我想知道是否有人知道如何使用CoreGraphics拍摄图像并添加光泽效果,就像您在iOS上看到的那样。具体来说,我想拍摄一张从网络上下载的图像,然后像这样设置它的样式。我搜索了很多东西,发现的只是在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提供有关添加光泽渐变的代码。
关于使用核心图形的iPhone光泽图标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5541457/