简体   繁体   中英

iOS: Draw shadow within UIView

I found some great code that is a subclass of UIView which draws that view with a shadow. Then I can use that view anywhere I want to place the shadow:

-(void) layoutSubviews {
    CGFloat coloredBoxMargin = 40;
    CGFloat coloredBoxHeight = self.frame.size.height;
    _coloredBoxRect = CGRectMake(coloredBoxMargin, 0, 40, coloredBoxHeight);
}

-(void) drawRect:(CGRect)rect {

    CGColorRef lightColor =  [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8].CGColor;
    CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;   

    CGContextRef context = UIGraphicsGetCurrentContext();
    // Draw shadow
    CGContextSaveGState(context);
    CGContextSetFillColorWithColor(context, lightColor);
    CGContextSetShadowWithColor(context, CGSizeMake(-13, 0), 10, shadowColor);

    CGContextFillRect(context, _coloredBoxRect);
    CGContextRestoreGState(context);
}

Created using the following:

UIViewWithShadowRight* verticalLineView2 = [[[UIViewWithShadowRight alloc] initWithFrame:CGRectMake(60, 0, 40 , self.view.frame.size.height)] autorelease];
[verticalLineView2 setBackgroundColor:[UIColor clearColor]];
[verticalLineView2 setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
[verticalLineView2 setClipsToBounds:NO];
[self.view addSubview:verticalLineView2];
[self.view bringSubviewToFront:verticalLineView2];

Problem is, the shadow is drawn from right to left, how can I reverse this and draw it left to right?

Make 13 positive instead of negative. That is the x-offset of the drawn shadow, with negative values being to the left of the original drawing, and positive values being to the right.

Try to change this CGContextSetShadowWithColor(context, CGSizeMake(-13, 0), 10, shadowColor); Replace the current x value (-13) to the value on the right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM