ios - CoreGraphics 矩形渐变

标签 ios core-graphics linear-gradients

有人可以帮我用 CoreGraphics 绘制一个特定的渐变吗? 只要给出线索就足够了。 示例代码值得我致以最深的敬意。 我需要这个形状:

enter image description here

我尝试了以下代码:

-(UIImage *)imageWithGradientBorder
{
    CGRect rect=CGRectMake(0, 0, self.size.width, self.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef ctx= CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, 8, rect.size.width, colorSpace, kCGImageAlphaNone);
    CGGradientRef glossGradient;
    size_t num_locations = 4;
    CGFloat locations[4] = { 0.0, 0.1, 0.9, 1.0 };
    CGFloat components[16] = { 0, 0, 0, 1, 1.0, 1.0, 1.0, 1, 1.0, 1.0, 1.0, 1, 0, 0, 0, 1};
    glossGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, num_locations);
    CGRect currentBounds = rect;

    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
    topCenter = CGPointMake( 0.0f, CGRectGetMidY(currentBounds));
    midCenter = CGPointMake(CGRectGetMaxX(currentBounds), CGRectGetMidY(currentBounds));

    CGContextDrawLinearGradient(ctx, glossGradient, topCenter, midCenter, 0);
    CGImageRef mask = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGImageRef maskedImageRef = CGImageCreateWithMask([self CGImage], mask);
    CGImageRelease(mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
    CGImageRelease(maskedImageRef);
    return maskedImage;
}

但它只从左侧绘制渐变。

最佳答案

topCenter = CGPointMake( 0.0f, CGRectGetMidY(currentBounds));
midCenter = CGPointMake(CGRectGetMaxX(currentBounds), CGRectGetMidY(currentBounds));

这两个变量的名称具有误导性,它们并不是真正的中上和中中,而是中左和中右。所以当你打电话时:

CGContextDrawLinearGradient(ctx, glossGradient, topCenter, midCenter, 0);

您正在从左到右绘制渐变。

您需要做什么来组织您的点并绘制渐变 4 次(L->R、R->L、T->B、B->T)。根据您希望角落看起来准确的样子,您可能需要在每个渐变绘制之间进行一些 mask ,以防止渐变一直绘制到角落中。

关于ios - CoreGraphics 矩形渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18918382/

相关文章:

iphone - 核心数据 NSObjectInaccessibleException NSManagedObject 已失效

ios - 当 UIApplicationWillEnterForeground 时运行动画

ios - 如何在 swift 中定义 CGPatternDrawPatternCallback

swift - 如何在 Swift 中识别使用 Core Graphics 绘制的形状?

html - 只有一个部分的 CSS 渐变方向

css - 矩形透明 Angular 的渐变?

css - 用线性渐变绘制左上三 Angular 形并将其放入容器中

ios - Apple Store - 拒绝使用 UIWebView 的新应用;这会影响我现有的应用程序和 future 的版本吗?

ios - Swift - 从 UIViewControllers 转到 'in' 和 'back' 时内存增加

ios - 在 iOS 中使用多点触控绘图撤消