Create UIImage from shadowed view while retaining alpha?

白昼怎懂夜的黑 提交于 2019-11-29 16:59:35
Benjie

Try setting your UIImageView's backgroundColor to [UIColor clearColor] - this may enable your current solution to work.

imageView.backgroundColor = [UIColor clearColor];
UIGraphicsBeginImageContext(CGSizeMake(320, 396)); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Source: Converting a CGLayer to a *transparent* UIImage and PNG file in CoreGraphics iphone

I've had this issue before too. My solution was not to do an image, but instead to set the shadow path to just the outline of the view you are animating.

[imageView setContentMode:UIViewContentModeScaleAspectFit];
imageView.layer.masksToBounds = NO;
imageView.layer.shadowOffset = CGSizeMake(5, 5);
imageView.layer.shadowRadius = 200;
imageView.layer.shadowOpacity = 0.5;
CGRect rect = [self rectFromImageView:imageView];
imageView.layer.shadowPath = [UIBezierPath bezierPathWithRect:rect].CGPath;

Which uses the following function which assumes the image is set to content mode aspect fit:

-(CGRect)rectFromImageView:(UIImageView *)iv {
    CGRect rect = (CGRect){{0,0},iv.frame.size};
    if (iv.image.size.width/iv.frame.size.width > iv.image.size.height/iv.frame.size.height) {
        //rect.origin.x == 0
        CGFloat sf = iv.frame.size.width/iv.image.size.width;
        rect.size.height = sf*iv.image.size.height;
        rect.origin.y = floor((iv.frame.size.height - rect.size.height)/2);
    } else {
        //rect.origin.y == 0;
        CGFloat sf = iv.frame.size.height/iv.image.size.height;
        rect.size.width = sf*iv.image.size.width;
        rect.origin.x = floor((iv.frame.size.width - rect.size.width)/2);       
    }
    return rect;
}

If your image is just set to fill then just using the imageView.bounds should be sufficient

setdvd

Add shadow path to view like this

[view.layer setShadowPath:[[UIBezierPath bezierPathWithRect:view.bounds] CGPath]]; //add path
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowOffset = CGSizeMake(x, y);
view.layer.shadowRadius = rad;
view.layer.shadowOpacity = 0.2f;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!