图片处理代码片段

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;

}

时间: 2024-11-13 06:41:48

图片处理代码片段的相关文章

关于UITabBar各部分自定义的代码片段

一.自定义TabBar选项卡背景默认UITabBarController的TabBar背景是黑色的,如何自定义成背景图片呢? UITabBarController *tabBarController = [[UITabBarController alloc] init]; // 获取选项卡控制器视图的所有子视图,保存到一数组中 NSArray *array = [tabBarController.view subviews]; // 索引值为1的应该就是TabBar UITabBar  *tab

10个常用的JQUERY代码片段

jQuery被用在无数个网站的页面上,它是使用最为广泛的javascript库之一.jQuery的受欢迎程度的部分是它的简单性.它能够通过简单的语句完成大部分复杂的工作.有许多jQuery片段我们在每天不断重复的使用,这里总结了10条你必须知道的jQuery代码片段. 返回顶部 <a class="top" href="#">Back to top</a> // Back To Top $('a.top').click(function(){

收集的35个 jQuery 小技巧/代码片段,可以帮你快速开发.

1. 禁止右键点击 $(document).ready(function(){     $(document).bind("contextmenu",function(e){         return false;     }); }); 2. 隐藏搜索文本框文字 Hide when clicked in the search field, the value.(example can be found below in the comment fields) $(document

【转】46 个非常有用的 PHP 代码片段

1. 发送 SMS 在开发 Web 或者移动应用的时候,经常会遇到需要发送 SMS 给用户,或者因为登录原因,或者是为了发送信息.下面的 PHP 代码就实现了发送 SMS 的功能. 为了使用任何的语言发送 SMS,需要一个 SMS gateway.大部分的 SMS 会提供一个 API,这里是使用 MSG91 作为 SMS gateway. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

WebApp 开发中常用的代码片段

其实这里面的多数都是 iOS 上面的代码.其他平台的就没有去验证了. HTML, 从HTML文档的开始到结束排列: <meta name=”viewport” content=”width=device-width, initial-scale=1.0″/> 让内容的宽度自适应为设备的宽度, 在做Mobile Web时必须加的一条 <meta name=”format-detection” content=”telephone=no”]]> 禁用手机号码链接(for iPhone)

30+有用的CSS代码片段

在一篇文章中收集所有的CSS代码片段几乎是不可能的事情,但是我们这里列出了一些相对于其他的更有用的代码片段,不要被这些代码的长度所吓到,因为它们都很容易实现,并且具有良好的文档.除了那些解决常见的恼人的问题外,也包含了一些解决新问题的新技术. 1. 垂直对齐 如果你之前遇到过这个问题,你就应该知道它是多么的烦人,幸运的是,现在你可以使用CSS3变换来解决这个问题: .vc{ position: relative; top: 50%; -webkit-transform: translateY(-

10个你必须知道的jQueryMobile代码片段(转)

1.在列表项和按钮上禁用文本截断      如果你的列表项或者按钮上是一个很长的文本,它将会被jQuery Mobile自动截断,要禁用这个截断设置,需要在CSS选择器上添加属性"white-space:normal".例如,在按钮禁止截断:      .ui-btn-text{           white-space:normal;      }      在列表项上禁止截断:      .ui-li-desc{           white-space:norma;     

最实用、最常用的jQuery代码片段

1 // chinacoder.cn JavaScript Document 2 3 $(document).ready(function() { 4 5 //.filter(":not(:has(.selected))") //去掉所有不包含class为.selected的元素 6 7 // 使用has()来判断一个元素是否包含特定的class或者元素 8 $("input").has(".email").addClass("emai

【转】30+有用的CSS代码片段

来自:WEB资源网 链接:http://webres.wang/31-css-code-snippets-to-make-you-a-better-coder/ 原文:http://www.designyourway.net/blog/resources/31-css-code-snippets-to-make-you-a-better-coder/ 在一篇文章中收集所有的CSS代码片段几乎是不可能的事情,但是我们这里列出了一些相对于其他的更有用的代码片段,不要被这些代码的长度所吓到,因为它们都