码迷,mamicode.com
首页 > 其他好文 > 详细

图片处理代码片段

时间:2015-08-02 14:58:06      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

 1. 图片缩放:
代码
- (UIImage*)resizeImage:(UIImage*)image toWidth:(NSInteger)width height:(NSInteger)height
{
    // Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    CGSize size = CGSizeMake(width, height);
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    else
        UIGraphicsBeginImageContext(size);
 
    CGContextRef context = UIGraphicsGetCurrentContext();
 
    // Flip the context because UIKit coordinate system is upside down to Quartz coordinate system
    CGContextTranslateCTM(context, 0.0, height);
    CGContextScaleCTM(context, 1.0, -1.0);
 
    // Draw the original image to the context
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), image.CGImage);
 
    // Retrieve the UIImage from the current context
    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();
 
    UIGraphicsEndImageContext();
 
    return imageOut;
}
 
    2.UIView旋转:
代码
- (void)rotateView:(UIView *)view toAngle:(float)angle
{
    [UIView beginAnimations:nil context:nil];
    [view setTransform:CGAffineTransformMakeRotation(angle)];
    [UIView commitAnimations];
}
 
    3.  颜色处理函数:
代码
 
#pragma mark Color convert
 
-(UIColor *) str2Color:(NSString *)str {
    SEL blackSel = NSSelectorFromString(str);//NSSelectorFromString(@"blackColor");
    UIColor* tColor = nil;
    if ([UIColor respondsToSelector: blackSel])
        tColor  = [UIColor performSelector:blackSel];
    return tColor;
}
 
-(UIColor *) hexStr2Color:(NSString *)hexStr {
    NSString *cString = [[hexStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
    
}
 
- (NSString *)color2str:(UIColor *)color {
    CGColorRef c = color.CGColor;
    const CGFloat *components = CGColorGetComponents(c);
    size_t numberOfComponents = CGColorGetNumberOfComponents(c);
    NSMutableString *s = [[[NSMutableString alloc] init] autorelease];
    [s appendString:@"{"];
    for (size_t i = 0; i < numberOfComponents; ++i) {
        if (i > 0) {
            [s appendString:@","];
        }
        [s appendString:[NSString stringWithFormat:@"%d", (int)(components[i]*255) ]];
    }
    [s appendString:@"}"];
    return s;
}
- (NSString *)color2str1:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    NSString *colorAsString = [NSString stringWithFormat:@"%1f,%1f,%1f,%1f", components[0]*255, components[1]*255, components[2]*255, components[3]];
}
 
 
    4.  三点坐标中间点对应的角度,以及判断是否顺时针 
代码
 
-(BOOL) chkClockWise:(CGPoint)a B:(CGPoint)b C:(CGPoint)c {
    double ax = a.x - b.x;
    double ay = - a.y + b.y;
    
    double cx = c.x - b.x;
    double cy = - c.y + b.y;
    
    NSLog(@"result:%d",(cy*ax)<=(ay*cx));
    NSLog(@"(x1,y1)=(%1f,%1f)",ax, ay);
    NSLog(@"(x2,y2)=(%1f,%1f)\r\n\r\n",cx, cy);
    
    return ((cy*ax)<=(ay*cx));
}
 
 
 
     5. 点坐标旋转后弧度后获取新的坐标:
代码
-(CGPoint) getNewPoint: (CGPoint)old rotate:(double)rotate{
    
    //实际坐标换算到原点坐标
    old.x =  (old.x-center.x);
    old.y = (center.y-old.y);
    
    //计算选转后新坐标
    double x = old.x*cos(rotate)-old.y*sin(rotate); 
    double y = old.y*cos(rotate)+old.x*sin(rotate);
 
    //原点坐标换算到实际坐标
    x = center.x + x;
    y = center.y - y;
    
    return CGPointMake(x, y);
}
 
 
     6. 抓取UIView上任意点的颜色:
代码
- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
    
 
    
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
 
    
    CGImageRef inImage = viewImage.CGImage;
 
    
    UIColor* color = nil;
    // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    if (cgctx == NULL) { return nil; /* error */ }
    
    
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}}; 
    
    // Draw the image to the bitmap context. Once we draw, the memory 
    // allocated for the context for rendering will then contain the 
    // raw image data in the specified color space.
    CGContextDrawImage(cgctx, rect, inImage); 
    
    // Now we can get a pointer to the image data associated with the bitmap
    // context.
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        //offset locates the pixel in the data from x,y. 
        //4 for 4 bytes of data per pixel, w is width of one row of data.
        int offset = 4*((w*round(point.y))+round(point.x));
        int alpha =  data[offset]; 
        int red = data[offset+1]; 
        int green = data[offset+2]; 
        int blue = data[offset+3]; 
        NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
    }
    
    // When finished, release the context
    CGContextRelease(cgctx); 
    // Free image data memory for the context
    if (data) { free(data); }
    
    return color;
}
 
- (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {
    
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    void *          bitmapData;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;
    
    // Get image width, height. We‘ll use the entire image.
    size_t pixelsWide = CGImageGetWidth(inImage);
    size_t pixelsHigh = CGImageGetHeight(inImage);
    
    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow   = (pixelsWide * 4);
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);
    
    // Use the generic RGB color space.
    colorSpace = CGColorSpaceCreateDeviceRGB();
    
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }
    
    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL) 
    {
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
    
    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits 
    // per component. Regardless of what the source image format is 
    // (CMYK, Grayscale, and so on) it will be converted over to the format
    // specified here by CGBitmapContextCreate.
    context = CGBitmapContextCreate (bitmapData,
                                     pixelsWide,
                                     pixelsHigh,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedFirst);
    if (context == NULL)
    {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }
    
    // Make sure and release colorspace before returning
    CGColorSpaceRelease( colorSpace );
    
    return context;
}
 
 
 
7. 在iphone程序中实现截屏的一种方法:
 
//导入头文件
#import <QuartzCore/QuartzCore.h>
 
//将整个self.view大小的图层内容创建一张图片image
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
 
//然后将该图片保存到图片图
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
 
8. 画圆点图片:
-(UIImage*)createImage
{
  CGSize size = [[UIScreen mainScreen] bounds].size;
  CGRect rect = CGRectMake( size.width/2,size.height/2, 5, 5);
  UIGraphicsBeginImageContext(size);
  CGContextRef context = UIGraphicsGetCurrentContext();
 
  unsigned int red, green, blue;
  // Fill color.
  CGContextSetRGBFillColor(context, 0, 0.7, 0.7, 1.0);
 
  // Your drawing code.
  CGContextFillEllipseInRect(context, rect);
 
  // Get the image and return.
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image;

 

图片处理代码片段

标签:

原文地址:http://www.cnblogs.com/OIMM/p/4695637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!