圖片處理程式碼片段,處理程式碼片段

來源:互聯網
上載者:User

圖片處理程式碼片段,處理程式碼片段
 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大小的圖層內容建立一張圖片imageUIGraphicsBeginImageContext(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;} 

 

   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.