在UIImage上绘制边框和阴影

Jos*_*eld 0 iphone objective-c uiimageview uiimage ios

我已经能够成功地重绘具有边框的UIImage,但没有边框+阴影.下面的代码成功地绘制了带有白色边框的图像,但我无法弄清楚如何在边框下包含阴影.非常感谢帮助!

- (UIImage *)generatePhotoFrameWithImage:(UIImage *)image {
CGSize newSize = CGSizeMake(image.size.width + 50, image.size.height + 60);
UIGraphicsBeginImageContext(newSize);
CGRect rect = CGRectMake(25, 35, image.size.width, image.size.height);
[image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextStrokeRectWithWidth(context, CGRectMake(25, 35, image.size.width, image.size.height), 50);

//CGContextSetShadowWithColor(context, CGSizeMake(0, -60), 5, [UIColor blackColor].CGColor);

UIImage *result =  UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return result; }
Run Code Online (Sandbox Code Playgroud)

PS:我没有使用UIImageView,因为我需要保持完整的图像质量.

rob*_*off 9

CGContextSetShadowWithColor在描边边界之前需要调用,因此边框会投射阴影.

如果您不希望边框在图像上投射阴影,则需要设置一个透明层,在该图层中绘制图像和边框.您可以在Quartz 2D Programming Guide中阅读有关透明度图层的信息.

如果要保留图像质量,则需要使用UIGraphicsBeginImageContextWithOptions并传入原始图像的比例.

- (UIImage *)generatePhotoFrameWithImage:(UIImage *)image {
    CGSize newSize = CGSizeMake(image.size.width + 50, image.size.height + 60);
    CGRect rect = CGRectMake(25, 35, image.size.width, image.size.height);

    UIGraphicsBeginImageContextWithOptions(newSize, NO, image.scale); {
        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextBeginTransparencyLayer(context, NULL); {
            [image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

            CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
            CGContextSetShadowWithColor(context, CGSizeMake(0, 5), 5, [UIColor blackColor].CGColor);
            CGContextStrokeRectWithWidth(context, CGRectMake(25, 35, image.size.width, image.size.height), 50);
        } CGContextEndTransparencyLayer(context);
    }
    UIImage *result =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 喜欢缩进风格!+1 (2认同)