获取倒立的图像


//.h

+ (UIImage *)invertedImageWith:(UIImageView *)image height:(NSUInteger)height;

//.m

+ (UIImage *)invertedImageWith:(UIImageView *)image height:(NSUInteger)height {

if(height == 0){

return nil;

}

CGContextRef mainViewContentContext = MyCreateBitmapContext(image.bounds.size.width, (int)height);

CGImageRef gradientMaskImage = CreateGradientImage(1, (int)height);

CGContextClipToMask(mainViewContentContext, CGRectMake(0.0, 0.0, image.bounds.size.width, height), gradientMaskImage);

CGImageRelease(gradientMaskImage);

CGContextTranslateCTM(mainViewContentContext, 0.0, height);

CGContextScaleCTM(mainViewContentContext, 1.0, -1.0);

CGContextDrawImage(mainViewContentContext, image.bounds, image.image.CGImage);

CGImageRef reflectionImage = CGBitmapContextCreateImage(mainViewContentContext);

CGContextRelease(mainViewContentContext);

UIImage *theImage = [UIImage imageWithCGImage:reflectionImage];

CGImageRelease(reflectionImage);

return theImage;

}

CGImageRef CreateGradientImage(int pixelsWide, int pixelsHigh){

CGImageRef cgimage = NULL;

CGColorSpaceRef space = CGColorSpaceCreateDeviceGray();

CGContextRef gradientBitmapContext = CGBitmapContextCreate(NULL, pixelsWide, pixelsHigh,8, 0, space, 0);

CGFloat colors[] = {0.0, 1.0, 1.0, 1.0};

CGGradientRef grayScaleGradient = CGGradientCreateWithColorComponents(space, colors, NULL, 2);

CGColorSpaceRelease(space);

CGPoint gradientStartPoint = CGPointZero;

CGPoint gradientEndPoint = CGPointMake(0, pixelsHigh);

CGContextDrawLinearGradient(gradientBitmapContext, grayScaleGradient, gradientStartPoint,gradientEndPoint,kCGGradientDrawsAfterEndLocation);

CGGradientRelease(grayScaleGradient);

cgimage = CGBitmapContextCreateImage(gradientBitmapContext);

CGContextRelease(gradientBitmapContext);

return cgimage;

}

CGContextRef MyCreateBitmapContext(int pixelsWide, int pixelsHigh){

CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();

CGContextRef bitmapContext = CGBitmapContextCreate (NULL, pixelsWide, pixelsHigh, 8,0, space,(kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst));

CGColorSpaceRelease(space);

return bitmapContext;

}

推荐阅读更多精彩内容