NSImage,CFImage常规操作转

NSImage的一个扩展

作者:Codelif

    学习了Cocoa的图片制作,受益很多。知道了图片是怎么画出来的。上层原理。可以对图片的图层操作,如添加一个图层,删除图层,图片的混合,图片的缩放,矢量图图的制作,把字符串图片化,制作pdf的一些原理等。

  1. //
  2. //  NSImage+ZCPanel.h
  3. //  Flected
  4. //
  5. //  Created by zhuzhichao on 08-12-11.
  6. //  Copyright 2008 __MyCompanyName__. All rights reserved.
  7. #import <Cocoa/Cocoa.h>
  8. #import "CTGradient.h"
  9. #define MAX_PIXEL_SIZE   600*800
  10. #define PIC_WIDTH  800
  11. #define PIC_HEIGHT 600
  12. //Picture fram
  13. /*
  14.    NSBMPFileType,
  15.    NSGIFFileType,
  16.    NSJPEGFileType,0); background-color: inherit; ">   NSPNGFileType,0); background-color: inherit; ">   NSJPEG2000FileType*/
  17. @interface NSImage (ZCPanel)
  18. + (NSImage *) prettyGradientImage:(NSSize)gradientSize;  // Generates a 256 by 256 pixel image with a complicated gradient in it.
  19. + (NSImage *) reflectedImage:(NSImage *)sourceImage amountReflected:(float)fraction;
  20. + (NSImage *) createScalesImage:(NSImage *)sourceImage flipFlag:(BOOL)bFlip amountReflected:( + (NSImage *) rotateImage:(NSImage*)sourceImage byDegrees:(float)deg;
  21. + (NSImage *) imageFromCGImageRef:(CGImageRef)image; //FROME CGImageRef to NSImage
  22. - (CGImageRef) nsImageToCGImageRef;//FROME  NSImage to CGImageRef
  23. - (BOOL) setSmoothingEffect; //Set smoothing effect
  24. BOOL) saveImage:(NSImage*)image 
  25.          saveType:(NSBitmapImageFileType)storageType
  26.          properties:(NSDictionary *)properties
  27.          ToTarget:(NSString *) targePath;
  28.          
  29. - (CGImageRef)thumbnailForFile: (NSString*)name atPath: (NSString*)filePath;
  30. @end
  31. //  AppController+ZCBundImage.m
  32. #import "NSImage+ZCPanel.h"
  33. float distance(NSPoint aPoint);
  34. enum pixelComponents { red, green, blue, alpha };
  35. #define PI 3.14159265358979323846264338327950288
  36. @implementation NSImage (ZCPanel)
  37. ////倒立,深度
  38. + (NSImage *)reflectedImage:(NSImage *)sourceImage amountReflected:(float)fraction
  39. {
  40.     NSImage *reflection = [[NSImage alloc] initWithSize:[sourceImage size]];
  41.     [reflection setFlipped:YES];
  42.     [reflection lockFocus];
  43.     CTGradient *fade = [CTGradient gradientWithBeginningColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.5] endingColor:[NSColor clearColor]];
  44.     [fade fillRect:NSMakeRect(0, 0, [sourceImage size].width, [sourceImage size].height*fraction) angle:90.0];  
  45.     [sourceImage drawAtPoint:NSMakePoint(0,0) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  46.     [reflection unlockFocus];
  47.     return [reflection autorelease];
  48. }
  49. //缩放到目的大小,太小了不缩放添加背景
  50. + (NSImage *)createScalesImage:(NSImage *)sourceImage flipFlag:(float)fraction
  51. {
  52.     //set flipped
  53.     [sourceImage setScalesWhenResized:YES];
  54.     if(bFlip)
  55.     {
  56.         [sourceImage setFlipped:YES];
  57.     }
  58.     
  59.     //source picture size
  60.     NSSize srcSize = [sourceImage size];
  61.     unsigned int uiWidth= srcSize.width;
  62.     unsigned int uiHeight= srcSize.height;
  63.     
  64. //target bg picture size
  65. int bgWidth = PIC_WIDTH;
  66. int bgHeight = PIC_HEIGHT;
  67.     NSSize tarSize =NSMakeSize(bgWidth, bgHeight);
  68.     if(uiWidth>=bgWidth && uiHeight >= bgHeight)
  69.     {
  70.         [sourceImage setSize:tarSize];
  71.         return [[sourceImage copy] autorelease];
  72.     if(uiWidth>bgWidth && uiHeight < bgHeight)
  73.         [sourceImage setSize:tarSize];
  74.         
  75.         //target bg picture
  76.         NSImage *targetImage = [[NSImage alloc] initWithSize:tarSize];
  77.         [targetImage lockFocus];
  78.         //fill target bg picture,using white color
  79.         [[NSColor whiteColor] set];
  80.         NSRectFill(NSMakeRect(0, bgWidth, bgHeight*fraction));
  81.         
  82. //draw
  83.         [sourceImage drawAtPoint:NSMakePoint(0,(bgHeight - uiHeight)*0.5) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  84.         [targetImage unlockFocus];
  85.         return [targetImage autorelease];
  86.     }
  87.     if(uiWidth<bgWidth && uiHeight >bgHeight)
  88. //target bg picture
  89.         NSImage *targetImage = [[NSImage alloc] initWithSize:tarSize];
  90.         [targetImage lockFocus];
  91.         [[NSColor whiteColor] set];
  92.         NSRectFill(NSMakeRect(0, bgWidth*fraction));
  93. //draw
  94.         [sourceImage drawAtPoint:NSMakePoint((bgWidth- uiWidth)*0.5, 0) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  95.         [targetImage unlockFocus];
  96.         return [targetImage autorelease];
  97.     else
  98. //(uiWidth<bgWidth && uiHeight < bgHeight)
  99. //[sourceImage setSize:tarSize];
  100.         [sourceImage drawAtPoint:NSMakePoint((bgWidth - uiWidth)*0.5, (bgHeight - uiHeight)*0.5) fromRect:NSZeroRect operation:NSCompositeSourceIn fraction:1.0];
  101. //按照图片的中心旋转90.180.270,360度
  102. float)deg
  103.     NSSize srcsize= [sourceImage size];
  104.     float srcw = srcsize.width;
  105.     float srch= srcsize.height;
  106. float newdeg = 0;
  107. //旋转弧度
  108. //double ratain = ((deg/180) * PI);
  109.     NSRect r1;
  110.     if(0< deg && deg <=90)
  111.         r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
  112.         newdeg = 90.0;
  113.     if(90< deg && deg <=180)
  114.         r1 = NSMakeRect(0, srcw, srch);
  115.         newdeg = 180.0;
  116.     if(180< deg && deg <=270)
  117.         newdeg = 270.0;
  118.     if(270< deg && deg <=360)
  119.         newdeg = 360;
  120. //draw new image
  121.     NSImage *rotated = [[NSImage alloc] initWithSize:[sourceImage size]];
  122.     [rotated lockFocus];
  123.     NSAffineTransform *transform = [NSAffineTransform transform];
  124.     [transform translateXBy:(0.5*srcw) yBy: (0.5*srch)];  //按中心图片旋转
  125.     [transform rotateByDegrees:newdeg];                   //旋转度数,rotateByRadians:使用弧度
  126.     [transform translateXBy:(-0.5*srcw) yBy: (-0.5*srch)];
  127.     [transform concat];
  128.     [[sourceImage bestRepresentationForDevice: nil] drawInRect: r1];//矩形内画图
  129. //[sourceImage drawInRect:r1 fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
  130. //[sourceImage drawAtPoint:arge/*NSZeroPoint*/ fromRect:NSMakeRect(arge.x, arge.y,ww ,wh)/*NSZeroRect*/ operation:NSCompositeCopy fraction:1.0];
  131.     [rotated unlockFocus];
  132.     return [rotated autorelease];
  133. //save image to file
  134. - (BOOL)saveImage:(NSImage*)image                      //source image
  135.          saveType:(NSBitmapImageFileType)storageType   //save type "NSJPEGFileType"
  136.          properties:(NSDictionary *)properties         //properties "NSImageCompressionFactor = (NSNumber)0.8"
  137.          ToTarget:(NSString *) targePath               //save path
  138.     NSData *tempdata;
  139.     NSBitmapImageRep *srcImageRep;
  140. BOOL reflag = NO;
  141.     [image lockFocus];
  142.     srcImageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
  143.     tempdata = [srcImageRep representationUsingType:storageType properties:properties];
  144.     reflag = [tempdata writeToFile:targePath atomically:YES];
  145.     [image unlockFocus];
  146.     return reflag;
  147. // ---------------------------------------------------------------------------------------------------------------------
  148. - (CGImageRef)thumbnailForFile: (NSString*)name
  149.                         atPath: (NSString*)filePath
  150. // use ImageIO to get a thumbnail for a file at a given path
  151.     CGImageSourceRef    isr = NULL;
  152.     NSString *          path = [filePath stringByExpandingTildeInPath];
  153.     CGImageRef          image = NULL;
  154.   //  path = [path stringByAppendingPathComponent: name];
  155. // create the CGImageSourceRef
  156.     isr = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath: path], NULL);
  157.     if (isr)
  158. // create a thumbnail:
  159. // - specify max pixel size
  160. // - create the thumbnail with honoring the EXIF orientation flag (correct transform)
  161. // - always create the thumbnail from the full image (ignore the thumbnail that may be embedded in the image -
  162. //                                                  reason: our MAX_ICON_SIZE is larger than existing thumbnail)
  163.         image = CGImageSourceCreateThumbnailAtIndex (isr, (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
  164.             [NSNumber numberWithInt: MAX_PIXEL_SIZE],  kCGImageSourceThumbnailMaxPixelSize,255); color: inherit; ">            (id)kCFBooleanTrue,                       kCGImageSourceCreateThumbnailWithTransform,92); margin-top: 0px !important; margin-right: 0px !important; margin-bottom: 0px !important; margin-left: 0px !important; line-height: 14px; list-style-type: decimal; padding-top: 2px; padding-right: 0px; padding-bottom: 2px; padding-left: 0px; ">            (id)kCFBooleanTrue,                       kCGImageSourceCreateThumbnailFromImageAlways,255); color: inherit; ">            NULL] );
  165.         CFRelease(isr);
  166.     return image;
  167. }
  168. + (NSImage*) imageFromCGImageRef:(CGImageRef)image
  169.     NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0);
  170.     CGContextRef imageContext = nil;
  171.     NSImage* newImage = nil;
  172. // Get the image dimensions.
  173.     imageRect.size.height = CGImageGetHeight(image);
  174.     imageRect.size.width = CGImageGetWidth(image);
  175. // Create a new image to receive the Quartz image data.
  176.     newImage = [[[NSImage alloc] initWithSize:imageRect.size] autorelease];
  177.     [newImage lockFocus];
  178. // Get the Quartz context and draw.
  179.     imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
  180.     CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
  181.     [newImage unlockFocus];
  182.     return newImage;
  183. - (CGImageRef)nsImageToCGImageRef//:(NSImage*)image;
  184.     NSData * imageData = [self TIFFRepresentation];
  185.     CGImageRef imageRef;
  186.     if(imageData)
  187.         CGImageSourceRef imageSource =
  188.          CGImageSourceCreateWithData(
  189.                             (CFDataRef)imageData,  NULL);
  190.         imageRef = CGImageSourceCreateImageAtIndex(
  191.                                imageSource,255); color: inherit; ">     return imageRef;
  192. BOOL)setSmoothingEffect
  193.     NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0];
  194.     NSSize size = NSMakeSize ([rep pixelsWide], [rep pixelsHigh]);
  195.     if(size.width >0 && size.height>0)
  196.         [self setSize: size];
  197.         return YES;
  198.     return NO;
  199.  // Generates a 256 by 256 pixel image with a complicated gradient in it.
  200. + (NSImage *) prettyGradientImage:(NSSize)gradientSize
  201.     NSImage *newImage = [[self alloc] initWithSize:gradientSize];  // In this case, the pixel dimensions match the image size.
  202. int pixelsWide = gradientSize.width;
  203. int pixelsHigh = gradientSize.height;    
  204.     NSBitmapImageRep *bitmapRep = 
  205.         [[NSBitmapImageRep alloc] 
  206.         initWithBitmapDataPlanes: nil  // Nil pointer makes the kit allocate the pixel buffer for us.
  207.         pixelsWide: pixelsWide  // The compiler will convert these to integers, but I just wanted to  make it quite explicit
  208.         pixelsHigh: pixelsHigh         bitsPerSample: 8
  209.         samplesPerPixel: 4  // Four samples, that is: RGBA
  210.         hasAlpha: YES
  211.         isPlanar: NO  // The math can be simpler with planar images, but performance suffers..
  212.         colorSpaceName: NSCalibratedRGBColorSpace  // A calibrated color space gets us ColorSync for free.
  213.         bytesPerRow: 0     // Passing zero means "you figure it out."
  214.         bitsPerPixel: 32];  // This must agree with bitsPerSample and samplesPerPixel.
  215.   
  216. char *imageBytes = [bitmapRep bitmapData];  // -bitmapData returns a void*, not an NSData object ;-)
  217. int row = pixelsHigh;
  218.     while(row--)
  219.         int col = pixelsWide;
  220.         while(col--) 
  221.         {
  222.             int 
  223.             pixelIndex = 4 * (row * pixelsWide + col);
  224.             imageBytes[pixelIndex + red] = rint(fmod(distance(NSMakePoint(col/1.5,(255-row)/1.5)),255.0));  //red
  225.             imageBytes[pixelIndex + green] = rint(fmod(distance(NSMakePoint(col/1.5, row/1.5)),0); background-color: inherit; ">// green
  226.             imageBytes[pixelIndex + blue] = rint(fmod(distance(NSMakePoint((255-col)/1.5,0); background-color: inherit; ">// blue
  227.             imageBytes[pixelIndex + alpha] = 255;  // Not doing anything tricky with the Alpha value here...
  228.         }
  229.     [newImage addRepresentation:bitmapRep];
  230.     return [newImage autorelease];
  231. float distance(NSPoint aPoint)  // Stole this from some guy named Pythagoras..  Returns the distance of aPoint from the origin.
  232.   return sqrt(aPoint.x * aPoint.x + aPoint.y *aPoint.y);
  233. //open selecter file panel
  234. /*static NSArray* openImageFiles()
  235.     // Get a list of extensions to filter in our NSOpenPanel.
  236.     NSOpenPanel* panel = [NSOpenPanel openPanel];
  237.     [panel setCanChooseDirectories:YES];    // The user can choose a folder; images in the folder are added recursively.
  238.     [panel setCanChooseFiles:YES];
  239.     [panel setAllowsMultipleSelection:YES];
  240.     if ([panel runModalForTypes:[NSImage imageUnfilteredFileTypes]] == NSOKButton)
  241.         return [panel filenames];
  242.     return nil;
  243. }*/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我正在用TitaniumDeveloper编写一个应用程序,它允许我使用Javascript,PHP,Ruby和Python.它为API提供了一些可能需要的标准功能,但缺少的是全局事件.现在我想将全局热键分配给我的应用程序并且几乎没有任何问题.现在我只针对MAC,但无法找到任何Python或Ruby的解决方案.我找到了Coc
我的问题是当我尝试从UIWebView中调用我的AngularJS应用程序中存在的javascript函数时,该函数无法识别.当我在典型的html结构中调用该函数时,该函数被识别为预期的.示例如下:Objective-C的:-(void)viewDidLoad{[superviewDidLoad];//CODEGOESHERE_webView.d
我想获取在我的Mac上运行的所有前台应用程序的应用程序图标.我已经使用ProcessManagerAPI迭代所有应用程序.我已经确定在processMode中设置了没有modeBackgroundOnly标志的任何进程(从GetProcessInformation()中检索)是一个“前台”应用程序,并显示在任务切换器窗口中.我只需要
我是一名PHP开发人员,我使用MVC模式和面向对象的代码.我真的想为iPhone编写应用程序,但要做到这一点我需要了解Cocoa,但要做到这一点我需要了解Objective-C2.0,但要做到这一点我需要知道C,为此我需要了解编译语言(与解释相关).我应该从哪里开始?我真的需要从简单的旧“C”开始,正
OSX中的SetTimer在Windows中是否有任何等效功能?我正在使用C.所以我正在为一些软件编写一个插件,我需要定期调用一个函数.在Windows上,我只是将函数的地址传递给SetTimer(),它将以给定的间隔调用.在OSX上有一个简单的方法吗?它应该尽可能简约.我并没有在网上找到任何不花哨的东西
我不确定引擎盖下到底发生了什么,但这是我的设置,示例代码和问题:建立:>雪豹(10.6.8)>Python2.7.2(由EPD7.1-2提供)>iPython0.11(由EPD7.1-2提供)>matplotlib(由EPD7.1-2提供)示例代码:importnumpyasnpimportpylabasplx=np.random.normal(size=(1000,))pl.plot
我正在使用FoundationFramework在Objective-C(在xCode中)编写命令行工具.我必须使用Objective-C,因为我需要取消归档以前由NSKeyedArchiver归档的对象.我的问题是,我想知道我现在是否可以在我的Linux网络服务器上使用这个编译过的应用程序.我不确定是否会出现运行时问题,或者可
使用cocoapods,我们首先了解一下rvm、gem、ruby。rvm和brew一样,但是rvm是专门管理ruby的版本控制的。rvmlistknown罗列出ruby版本rvminstall版本号   可以指定更新ruby版本而gem是包管理gemsource-l查看ruby源gemsource-rhttps://xxxxxxxx移除ruby源gemsou
我有一个包含WebView的Cocoa应用程序.由于应用程序已安装客户群,我的目标是10.4SDK.(即我不能要求Leopard.)我有两个文件:index.html和data.js.在运行时,为了响应用户输入,我通常会使用应用程序中的当前数据填充data.js文件.(data.js文件由body.html上的index.html文件用于填充
如何禁用NSMenuItem?我点击后尝试禁用NSMenuItem.操作(注销)正确处理单击.我尝试通过以下两种方式将Enabled属性更改为false:partialvoidLogout(AppKit.NSMenuItemsender){sender.Enabled=false;}和partialvoidLogout(AppKit.NSMenuItemsender){LogoutI
我在想,创建一个基本上只是一个带Web视图的界面的Cocoa应用程序是否可行?做这样的事情会有一些严重的限制吗?如果它“可行”,那是否也意味着你可以为Windows应用程序做同样的事情?解决方法:当然可以创建一个只是一个Cocoa窗口的应用程序,里面有一个Web视图.这是否可以被称为“可可应
原文链接:http://www.cnblogs.com/simonshi2012/archive/2012/10/08/2715464.htmlFrom:http://www.idev101.com/code/Cocoa/Notifications.htmlNotificationsareanincrediblyusefulwaytosendmessages(anddata)betweenobjectsthatotherwi
如果不手动编写GNUmake文件,是否存在可以理解Xcode项目的任何工具,并且可以直接针对GNUstep构建它们,从而生成Linux可执行文件,从而简化(略微)保持项目在Cocoa/Mac和GNUstep/Linux下运行所需的工作?基本上,是否有适用于Linux的xcodebuild样式应用程序?几个星期前我看了pbtomake
我正在将页面加载到WebView中.该页面有这个小测试Javascript:<scripttype="text/javascript">functiontest(parametr){$('#testspan').html(parametr);}varbdu=(function(){return{secondtest:function(parametr){$('#testspan&#039
我正在尝试使用NSAppleScript从Objective-C执行一些AppleScript…但是,我正在尝试的代码是Yosemite中用于自动化的新JavaScript.它在运行时似乎没有做任何事情,但是,正常的AppleScript工作正常.[NSAppactivateIgnoringOtherApps:YES];NSAppleScript*scriptObject=[[NSApple
链接:https://pan.baidu.com/s/14_im7AmZ2Kz3qzrqIjLlAg           vjut相关文章Python与Tkinter编程ProgrammingPython(python编程)python基础教程(第二版)深入浅出PythonPython源码剖析Python核心编程(第3版)图书信息作者:Kochan,StephenG.出
我正在实现SWTJava应用程序的OSX版本的视图,并希望在我的SWT树中使用NSOutlineView提供的“源列表”选项.我通过将此代码添加到#createHandle()方法来破解我自己的Tree.class版本来实现这一点:longNSTableViewSelectionHighlightStyleSourceList=1;longhi=OS.sel_regist
我的Cocoa应用程序需要使用easy_install在用户系统上安装Python命令行工具.理想情况下,我想将一个bash文件与我的应用程序捆绑在一起然后运行.但据我所知这是不可能的,因为软件包安装在Python的“site-packages”目录中.有没有办法创建这些文件的“包”?如果没有,我应该如何运行ea
摘要: 文章工具 收藏 投票评分 发表评论 复制链接 Swing 是设计桌面应用程序的一个功能非常强大工具包,但Swing因为曾经的不足常常遭到后人的诟病.常常听到旁人议论纷纷,”Swing 运行太慢了!”,”Swing 界面太丑嘞”,甚至就是说”Swing 简直食之无味”. 从Swing被提出到现在,已是十年光景,Swing早已不是昔日一无是处的Swing了. Chris Adamson 和我写
苹果的开发:   我对于Linux/Unix的开发也是一窍不通,只知道可以用Java.不过接触了苹果过后,确实发现,世界上确实还有那么一帮人,只用苹果,不用PC的.对于苹果的开发,我也一点都不清楚,以下是师兄们整理出来的网站. http://www.chezmark.com/osx/    共享软件精选 http://www.macosxapps.com/    分类明了,更新及时的一个重要Mac