通过向现有UIImage添加阴影来创建新的UIImage [英] Create new UIImage by adding shadow to existing UIImage

查看:191
本文介绍了通过向现有UIImage添加阴影来创建新的UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这个问题: UIImage Shadow Trouble

但是接受的答案对我来说不起作用。

But the accepted answer didn't work for me.

我想要做的是拿一个UIImage并添加一个阴影,然后返回一个全新的UIImage,shadow和所有。

What I'm trying to do is take a UIImage and add a shadow to it, then return a whole new UIImage, shadow and all.

这是我想尝试:

- (UIImage*)imageWithShadow {

    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef shadowContext = CGBitmapContextCreate(NULL, self.size.width, self.size.height + 1, CGImageGetBitsPerComponent(self.CGImage), 0, 
                                                 colourSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    CGContextSetShadow(shadowContext, CGSizeMake(0, -1), 1);
    CGContextDrawImage(shadowContext, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage);

    CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
    CGContextRelease(shadowContext);

    UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
    CGImageRelease(shadowedCGImage);

    return shadowedImage;
}

结果是我得到的图像与之前的图像完全相同这个方法。

The result is that I get exactly the same image as before I put it through this method.

我这样做是正确的方法,还是有一些明显的缺失?

I am doing this the correct way, or is there something obvious I'm missing?

推荐答案

您的代码有几个问题:


  • 目标图片太小。

  • 请考虑使用 CGContextSetShadowWithColor 来定义阴影及其颜色。

  • 不要忘记坐标系被翻转,所以原点是左下角,而不是左上角。

  • 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;
}

这篇关于通过向现有UIImage添加阴影来创建新的UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆