Create new UIImage by adding shadow to existing UIImage

后端 未结 8 869
半阙折子戏
半阙折子戏 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-09 00:10

    I needed a method that would accept an UIImage as a parameter and return a slightly larger UIImage with shadows. The posts here have been very helpful to me so here's my method. The returned image has a centered 5px shadow on each side.

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

提交回复
热议问题