Create new UIImage by adding shadow to existing UIImage

后端 未结 8 850
半阙折子戏
半阙折子戏 2020-12-08 23:15

I\'ve taken a look at this question: UIImage Shadow Trouble

But the accepted answer didn\'t work for me.

What I\'m trying to do is take a UIImage and add a s

8条回答
  •  萌比男神i
    2020-12-09 00:12

    There are several problems with your code:

    • The target image is too small. Be sure there enough place to draw the shadow.
    • Consider using CGContextSetShadowWithColor to define both the shadow and its color.
    • Don't forget that coordinate system is flipped, so the origin is bottom-left, not top-left.

    By fixing these issues, the shadow should be drawn.

    - (UIImage*)imageWithShadow {
        CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef shadowContext = CGBitmapContextCreate(NULL, self.size.width + 10, self.size.height + 10, CGImageGetBitsPerComponent(self.CGImage), 0, 
                                                 colourSpace, kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(colourSpace);
    
        CGContextSetShadowWithColor(shadowContext, CGSizeMake(5, -5), 5, [UIColor blackColor].CGColor);
        CGContextDrawImage(shadowContext, CGRectMake(0, 10, self.size.width, self.size.height), self.CGImage);
    
        CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
        CGContextRelease(shadowContext);
    
        UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
        CGImageRelease(shadowedCGImage);
    
        return shadowedImage;
    }
    

提交回复
热议问题