Create new UIImage by adding shadow to existing UIImage

后端 未结 8 845
半阙折子戏
半阙折子戏 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条回答
  •  失恋的感觉
    2020-12-08 23:49

    I needed a bigger shadow for my UIImages. Here is my variant of the answer that allows for a customized shadow size with no offset.

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

    Use it like:

    UIImage *shadowedImage = [self imageWithShadow:myImage BlurSize:30.0f];
    

提交回复
热议问题