簡體   English   中英

繪制帶有漸變和陰影的圓形UIView

[英]Draw a rounded UIView with gradient and drop shadow

編輯:

我終於找到了一個真正簡單的解決方案,使用CAGradientLayer類和CALayer繪圖功能。
Ole Begemann為名為OBGradientView的 CAGradientLayer類發布了一個很棒的UIView包裝器。
該類允許您在應用程序中輕松創建漸變UIView。
然后使用CALayer繪圖功能添加圓角和投影值:

// Create the gradient view
OBGradientView *gradient = [[OBGradientView alloc] initWithFrame:someRect];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], nil];
gradient.colors = colors;

// Set rounded corners and drop shadow
gradient.layer.cornerRadius = 5.0;
gradient.layer.shadowColor = [UIColor grayColor].CGColor;
gradient.layer.shadowOpacity = 1.0;
gradient.layer.shadowOffset = CGSizeMake(2.0, 2.0);
gradient.layer.shadowRadius = 3.0;

[self.view addSubview:gradient];
[gradient release];

別忘了將QuartzCore框架添加到您的項目中。



原始問題:

我一直在研究一個自定義控件,它是一個圓角矩形按鈕,填充線性漸變,並有一個投影。 我使用這個答案填寫了前兩個步驟: 鏈接文本

我現在的問題是在生成的形狀下添加一個陰影。 實際上,上下文被剪切到圓角矩形路徑,所以當我使用CGContextSetShadow函數時,它不會繪制它。

我嘗試通過繪制圓角矩形兩次來解決這個問題,首先使用普通顏色,因此它繪制陰影,然后使用漸變填充重繪它。

它有點工作,但我仍然可以在第一次使用普通顏色繪制時看到形狀角落處的幾個像素,正如您在此縮放版本上看到的那樣:

http://img269.imageshack.us/img269/6489/capturedcran20100701192.png

它幾乎是好的,但還不完美......

這是我的-drawRect:實現:

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


- (void)drawRect:(CGRect)rect
{ 
 CGContextRef context = UIGraphicsGetCurrentContext();

 CGSize shadowOffset = CGSizeMake(10.0, 10.0);
 CGFloat blur = 5.0;

 rect.size.width -= shadowOffset.width + blur;
 rect.size.height -= shadowOffset.height + blur;

 CGContextSaveGState(context);
 addRoundedRectToPath(context, rect, _radius, _radius);
 CGContextSetShadow (context, shadowOffset, blur);
 CGContextDrawPath(context, kCGPathFill);
 CGContextRestoreGState(context);

 addRoundedRectToPath(context, rect, _radius, _radius);
    CGContextClip(context);

 CGFloat colors[] =
 {
  _gradientStartColor.red, _gradientStartColor.green, _gradientStartColor.blue, _gradientStartColor.alpha,
  _gradientEndColor.red, _gradientEndColor.green, _gradientEndColor.blue, _gradientEndColor.alpha
 };
 size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };

 CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
 CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, locations, num_locations);

 CGRect currentBounds = self.bounds;
 CGPoint gStartPoint = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
 CGPoint gEndPoint = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
 CGContextDrawLinearGradient(context, gradient, gStartPoint, gEndPoint, 0);

 CGColorSpaceRelease(rgb);
 CGGradientRelease(gradient);
}

關於如何以另一種方式做到這一點的任何想法?

謝謝 !

為了創建一個帶有漸變背景和投影的圓角視圖,這是做了什么:

第一部分與問題中提供的內容非常相似,它使用CGPathAddArcToPoint創建一個圓角矩形路徑,如本文所述 這是一張圖片,可以幫助我理解它: 替代文字

第二部分的工作原理如下:

在圖形上下文中啟用陰影,添加剛剛定義的路徑,然后填充該路徑。 您不能僅將陰影應用於路徑本身(路徑不是圖形狀態的一部分),因此您需要填充路徑以便顯示陰影(我猜一條描邊路徑也可能起作用?)。 您不能簡單地將陰影應用於漸變,因為它不是真正的標准填充(有關詳細信息,請參閱此文章 )。

一旦你有一個填充圓角矩形創建陰影,你需要在其上方繪制漸變。 因此,第二次添加路徑以設置剪切區域,然后使用CGContextDrawLinearGradient繪制漸變。 我認為您不能像使用早期標准填充步驟那樣使用漸變輕松“填充”路徑,因此請使用漸變填充繪圖區域,然后剪切到您感興趣的圓角矩形區域在。

- (void)drawRect:(CGRect)rect 
{
    [super drawRect:rect];

    CGGradientRef gradient = [self normalGradient];

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGMutablePathRef outlinePath = CGPathCreateMutable(); 
    float offset = 5.0;
    float w  = [self bounds].size.width; 
    float h  = [self bounds].size.height; 
    CGPathMoveToPoint(outlinePath, nil, offset*2.0, offset); 
    CGPathAddArcToPoint(outlinePath, nil, offset, offset, offset, offset*2, offset); 
    CGPathAddLineToPoint(outlinePath, nil, offset, h - offset*2.0); 
    CGPathAddArcToPoint(outlinePath, nil, offset, h - offset, offset *2.0, h-offset, offset); 
    CGPathAddLineToPoint(outlinePath, nil, w - offset *2.0, h - offset); 
    CGPathAddArcToPoint(outlinePath, nil, w - offset, h - offset, w - offset, h - offset * 2.0, offset); 
    CGPathAddLineToPoint(outlinePath, nil, w - offset, offset*2.0); 
    CGPathAddArcToPoint(outlinePath, nil, w - offset , offset, w - offset*2.0, offset, offset); 
    CGPathCloseSubpath(outlinePath); 

    CGContextSetShadow(ctx, CGSizeMake(4,4), 3); 
    CGContextAddPath(ctx, outlinePath); 
    CGContextFillPath(ctx); 

    CGContextAddPath(ctx, outlinePath); 
    CGContextClip(ctx);
    CGPoint start = CGPointMake(rect.origin.x, rect.origin.y);
    CGPoint end = CGPointMake(rect.origin.x, rect.size.height);
    CGContextDrawLinearGradient(ctx, gradient, start, end, 0);

    CGPathRelease(outlinePath);
}

- (CGGradientRef)normalGradient
{

    NSMutableArray *normalGradientLocations = [NSMutableArray arrayWithObjects:
                                               [NSNumber numberWithFloat:0.0f],
                                               [NSNumber numberWithFloat:1.0f],
                                               nil];


    NSMutableArray *colors = [NSMutableArray arrayWithCapacity:2];

    UIColor *color = [UIColor colorWithRed:0.2745 green:0.2745 blue:0.2745 alpha:1.0];
    [colors addObject:(id)[color CGColor]];
    color = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    [colors addObject:(id)[color CGColor]];
    NSMutableArray  *normalGradientColors = colors;

    int locCount = [normalGradientLocations count];
    CGFloat locations[locCount];
    for (int i = 0; i < [normalGradientLocations count]; i++)
    {
        NSNumber *location = [normalGradientLocations objectAtIndex:i];
        locations[i] = [location floatValue];
    }
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

    CGGradientRef normalGradient = CGGradientCreateWithColors(space, (CFArrayRef)normalGradientColors, locations);
    CGColorSpaceRelease(space);

    return normalGradient;
}

我有解決方案,不需要預填充路徑。 優點(?)是陰影可以使用漸變的透明效果(即,如果漸變從不透明到透明,陰影也將部分透明)並且更簡單。

它或多或少像:

CGContextSetShadowWithColor();
CGContextBeginTransparencyLayer();

CGContextSaveGState();
CGContextClip();
CGGradientCreateWithColorComponents();
CGContextRestoreGState();

CGContextEndTransparencyLayer();
CGContextSetShadowWithColor(..., NULL);

我想這是因為CGContextBeginTransparencyLayer / CGContextEndTransparencyLayer在剪輯之外並且陰影應用於該層(其包含漸變填充路徑)。 至少它似乎對我有用。

對於陰影,您可以使用CGContextSetShadow()

這段代碼會用陰影繪制一些東西:

- (void)drawTheRealThingInContext:(CGContextRef)ctx 
{   
        // calculate x, y, w, h and inset here...

    CGContextMoveToPoint(ctx, x+inset, y);
    CGContextAddLineToPoint(ctx, x+w-inset, y);
    CGContextAddArcToPoint(ctx, x+w, y, x+w, y+inset, inset);
    CGContextAddLineToPoint(ctx, x+w, y+w-inset);
    CGContextAddArcToPoint(ctx,x+w, y+w, x+w-inset, y+w, inset);
    CGContextAddLineToPoint(ctx, x+inset, y+w);
    CGContextAddArcToPoint(ctx,x, y+w, x, y+w-inset, inset);
    CGContextAddLineToPoint(ctx, x, y+inset);
    CGContextAddArcToPoint(ctx,x, y, x+inset, y, inset);    
}
- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGFloat color[4];color[0] = 1.0;color[1] = 1.0;color[2] = 1.0;color[3] = 1.0;
    CGFloat scolor[4];scolor[0] = 0.4;scolor[1] = 0.4;scolor[2] = 0.4;scolor[3] = 0.8;

    CGContextSetFillColor(ctx, color);

    CGContextSaveGState(ctx);
    CGSize  myShadowOffset = CGSizeMake (3,  -3);
    CGContextSetShadow (ctx, myShadowOffset, 1);

    CGContextBeginPath(ctx);

    [self drawTheRealThingInContext:ctx];

    CGContextFillPath(ctx);
    CGContextRestoreGState(ctx);
}

您(原始)的問題是,當您繪制漸變時,您再次繪制陰影。 這個陰影有一個(0,0)偏移和一點點模糊,只有角落才會閃耀。 在CGContextDrawLinearGradient(...)之前的行中,添加以下內容:

CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 0, NULL);

NULL顏色值禁用陰影並將刪除角落效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM