博客首页|TW首页| 同事录|业界社区

一个人的精彩

iphone中获取两个矩形的相交区域

//definiton a rect
CGRect rect1 = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);

//获取2个矩形的相交区域
rect = CGRectIntersection(rect, bounds);

//create smaller or bigger rect(have same center)
CGRect rect2 = CGRectInset(rect, 32.0f, 32.0f);

//CGRect and NSString
NSString *string = NSStringFromCGRect(rect1);
rect1 = CGRectFromString(string);

//zero
CGRectZero

//full screen rect
[[UIScreen mainScreen] applicationFrame];

常用函数:
CGRectContainsPoint();    //点是否在矩形中
CGRectContainsRect();     //返回是否第一个矩形包含了第二长方形
CGRectIntersectsRect();     //返回两个矩形是否相交
CGRectIntersection();        //两个矩形的相交
CGPointEqualToPoint();     //两个点是否是一个点
CGSizeEqualToSize();       //两个size是否一样

浏览数: 次 星期三, 02月 29th, 2012 未分类 没有评论

iPhone开发小技巧集合

1。给iPhone程序创建Splash欢迎界面

最简单的方法就是做一个全屏的欢迎页的图片,把它命名为Default.png,然后放在Xcode工程的Resource里面。 执行就可以看到你的这个默认图像在程序完全加载之前显示在屏幕上。

Default.png是一张480*320的png图片用于在程序启动时显示。启动时,系统会用这张图片作为临时背景,直到程序载入了他的窗口和用户界面。

Icon.png是一张57*57的png图片,用于在iPhone的主界面上作为程序图标代表你的程序。这张图片不需要有其他附加特效,系统会自动添加这些效果。

Icon-Setting.png是一张29*29的png图片,用于在设置程序中作为图标代表你的程序。如果你的程序有Settings.bundle,这个图标将会显示在程序名的旁边。如果你没有设置这张图片,系统会将Icon.png缩放来代替。

2。 怎样才能让程序在运行过程中不锁屏呢?

[UIApplication sharedApplication].idleTimerDisabled=YES;//not let iphone go to sleep

3。显示被view 或 control遮盖的背景内容

xx.backgroundColor=[UIColor clearColor];

4。url编码

NSString *strURL = @”http://www.google.com/search?hl=en&newwindow=1&q=如何对url编码&aq=f&oq=&aqi=”;

strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //使用utf8

strURL=[strURLstringByAddingPercentEscapesUsingEncoding: CFStringConvertEncodingToNSStringEncoding( kCFStringEncodingGB_18030_2000)] ;////使用 gb2312

5。转换网页编码gb2312 -> utf

//编码转换 gb2313 to UTF
NSData * myResponseData = [myRequest responseData];
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
NSString * myResponseStr = [[NSString alloc] initWithData:myResponseData encoding:enc];
6。获取界面语言设置

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

浏览数: 次 星期一, 02月 27th, 2012 未分类 没有评论

图片缩放

// int h = image.size.height;
// int w = image.size.width;
// // if(h <= 320 && w <= 480)
//// {
////
//// }
//// else
//// {
// //float b = (float)320/w < (float)480/h ? (float)320/w : (float)480/h;
// //float b=0.5f;
// CGSize itemSize = CGSizeMake(w/2, h/2);
// UIGraphicsBeginImageContext(itemSize);
// CGRect imageRect = CGRectMake(0, 0, w/2, h/2);
// [image drawInRect:imageRect];
// image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// //}

浏览数: 次 星期六, 02月 25th, 2012 未分类 没有评论

code调试技巧(预处理器控制输出打印信息)

iPhone 应用发布后,程序运行过程中尽量不要有调试 log 信息输出,这样会影响程序运行的效率。通过宏定义设置,使程序只在 debug 模式下输出对我们有用的信息, release 时不会输出。
1、首先建立一个宏定义文件,文件内容如下:
#if DEBUG
#define debuglog(format, …)   NSLog(format, __VA_ARGS__)
#else
#define debuglog(format, …)
#endif

2,打开project–>edit project setting 中bulid选项卡

选择 左上角的 Configuration 的 Debug,下面的下拉框选择->Edit Definition at this Level ,在下面找GCC4.2-preprocessing-preprocessor macros(预处理器)设置DEBUG=1

这样我们就可以做到log调试信息在release时不会输出。

浏览数: 次 星期日, 02月 19th, 2012 未分类 没有评论

获取图片尺寸大小

UIImageView *im = [[UIImageView alloc] init];

im.image = [UIImage imageNamed:@"datu2.png"];

NSLog(@”image.size :%f,%f”,[im image].size.width,[im image].size.height) ;

浏览数: 次 星期六, 02月 18th, 2012 未分类 没有评论

解决图片同步数据卡的原因

NSData *data = nil;

if(stuffArray == nil) {

stuffArray = [[NSMutableArray array] retain];

}

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", @"Name", dataCover];

NSArray *filterArray = [stuffArray filteredArrayUsingPredicate:predicate];

//查找缓存图片

if(filterArray && [filterArray count]) {

NSDictionary *item = [filterArray objectAtIndex:0];

data = [item valueForKey:@"Data"];

} else {

NSURL *url = [NSURL URLWithString:dataCover];

data = [NSData dataWithContentsOfURL:url];

[stuffArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:dataCover,@"Name",data,@"Data",nil]];

}

UIImage *image = [[[UIImage alloc]initWithData:data]autorelease];

UIImageView *imageView = (UIImageView*)[cell viewWithTag:1];

imageView.image = image;

浏览数: 次 星期三, 02月 15th, 2012 未分类 没有评论

iphone开发常用代码

更改cell选中的背景
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;

在数字键盘上添加button:
//定义一个消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注册一个观察员 name:消息名称
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
[doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];

// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回应用程序window
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) //遍历window上的所有subview
{
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@”<UIKeyboard”] == YES)
[keyboard addSubview:doneButton];
}
}

正则表达式使用
被用于正则表达式的字串必须是可变长的,不然会出问题

将一个空间放在视图之上
[scrollView insertSubview:searchButton aboveSubview:scrollView];

从本地加载图片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src='0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];

从网页加载图片并让图片在规定长宽中缩小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];
将网页加载到webview上通过javascript获取里面的数据,如果只是发送了一个连接请求获取到源码以后可以用正则表达式进行获取数据
NSString *javaScript1 = @”document.getElementsByName(’.u’).item(0).value”;
NSString *javaScript2 = @”document.getElementsByName(’.challenge’).item(0).value”;
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];

用NSString怎么把UTF8转换成unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];

View自己调用自己的方法:
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黄色段为方法名,和延迟几秒执行.

显示图像:
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];

WebView:
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @”http://www.google.com“;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];

显示网络活动状态指示符
这是在iPhone左上部的状态栏显示的转动的图标指示有背景发生网络的活动。
UIApplication* app = [UIApplication sharedApplication];
  UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages; //animationImages属性返回一个存放动画图片的数组
myAnimatedView.animationDuration = 0.25; //浏览整个图片一次所用的时间
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 动画重复次数
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];

动画:显示了something在屏幕上移动。注:这种类型的动画是“开始后不处理” -你不能获取任何有关物体在动画中的信息(如当前的位置) 。如果您需要此信息,您会手动使用定时器去调整动画的X和Y坐标
这个需要导入QuartzCore.framework
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];

Draggable items//拖动项目
Here’s how to create a simple draggable image.//这是如何生成一个简单的拖动图象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point 检索接触点
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Move relative to the original touch point 相对以前的触摸点进行移动
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
3. Now instantiate the new class as you would any other new image and add it to your view
//实例这个新的类,放到你需要新的图片放到你的视图上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];

线程:
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user’s Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it’s not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
{
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@”plist”];
}
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];

Alerts
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@”An Alert!” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];
[alert show];
[alert release];

Info button
Increase the touchable area on the Info button, so it’s easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];

Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the “tag” property on your views.
for (UIImageView *anImage in [self.view subviews])
{
if (anImage.tag == 1)
{ // do something }
}

iphone(objective-c)相当于j2me的drawRegion方法 截取部分图片显示到指定位置

图片(UIImage*) img

要截取的起始坐标sx:(int) sx1 sy:(int)sy1

要截取的长度和宽度sw:(int) sw1 sh:(int) sh1

最终要显示的坐标desx:(int) desx1 desy:(int)desy1

-(UIImage*)objectiveDrawRegion:(UIImage*) img sx:(int) sx1 sy:(int)sy1 sw:(int) sw1 sh:(int) sh1 desx:(int) desx1 desy:(int)desy1{

[self saveImage:img name:@"objectiveDrawRegion1.png"];

//创建图片缓冲

void *imageDataRegion=malloc(screenWidth*screenHeight*32);

CGColorSpaceRef iColorSpaceRegion=CGColorSpaceCreateDeviceRGB();

CGContextRef iDeviceRegion=CGBitmapContextCreate(imageDataRegion,screenWidth,screenHeight,8,4*screenWidth,iColorSpaceRegion,kCGImageAlphaPremultipliedLast);

//剪切区域

CGRect clipRegion=CGRectMake(sx1,sy1,sw1,sh1);

CGContextClipToRect(iDeviceRegion, clipRegion);

CGFloat widthf=img.size.width;

CGFloat heightf=img.size.height;

CGRect cg=CGRectMake(0.0, 0.0, widthf, heightf);

//画底图

CGContextDrawImage(iDeviceRegion,cg, img.CGImage);

//将缓冲形成图片

CGImageRef ioffRegion=CGBitmapContextCreateImage(iDeviceRegion);

CGRect cg1=CGRectMake(desx1, desy1, sw1, sh1);

UIImage *ui=[UIImage imageWithCGImage:ioffRegion];

CGContextDrawImage(当前context,cg1, ui.CGImage);

//清除缓冲

CGColorSpaceRelease(iColorSpaceRegion);

CGContextRelease(iDeviceRegion);

CGImageRelease(ioffRegion);

free(imageDataRegion);

// iDeviceRegion=NULL;

// imageDataRegion=0;

return ui;

}

//这个方法更高效

/*

实现j2medrawRegion方法

sx 图片剪切的x位置

sy 图片剪切的y位置

sw 图片剪切的宽度

sh 图片剪切的高度

dx 剪切后的x位置

dy 剪切后的y位置

device 上下文

*/

-(void) objectiveDrawRegion:(UIImage*) img

sx:(int) sx1

sy:(int) sy1

sw:(int) sw1

sh:(int) sh1

dx:(int) dx1

dy:(int) dy1

device:(CGContextRef)idevicecopyOffscr

{

CGRect rect = CGRectMake(sx1, sy1, sw1, sh1);

CGImageRef imgRef = CGImageCreateWithImageInRect(img.CGImage, rect);

int dy1Trans = screenHeight - dy1 - sh1;

CGContextDrawImage(idevicecopyOffscr

, CGRectMake(dx1, dy1Trans, sw1, sh1)

, imgRef);

CGImageRelease(imgRef);

浏览数: 次 星期五, 02月 10th, 2012 未分类 没有评论

iOS平台XML解析类库对比和安装说明

在iPhone开发中,XML的解析有很多选择,iOS SDK提供了NSXMLParser和libxml2两个类库,另外还有很多第三方类库可选,例如TBXML、TouchXML、KissXML、TinyXML和GDataXML。问题是应该选择哪一个呢?

解析 XML 通常有两种方式,DOM 和 SAX:

  • DOM解析XML时,读入整个XML文档并构建一个驻留内存的树结构(节点树),通过遍历树结构可以检索任意XML节点,读取它的属性和值。而且通常情况下,可以借助XPath,直接查询XML节点。
  • SAX解析XML,是基于事件通知的模式,一边读取XML文档一边处理,不必等整个文档加载完之后才采取操作,当在读取解析过程中遇到需要处理的对象,会发出通知对其进行处理。

一般在iOS平台下,比较常用的XML解析类库有如下几种:

GDataXML

1. 从http://code.google.com/p/gdata-objectivec-client/downloads/list下载“gdata-objective-c client library.”

2. 解压缩文件,找到Source\XMLSupport,并且将其中的GDataXMLNode.h 和 GDataXMLNode.m文件拖到项目中

3. 选中项目,选中“Build Settings”标签页

4. 将Build Settings页中,顶部的“Basic”标签切换到“All”

5. 找到“Paths\Header Search Paths”项,并添加“/usr/include/libxml2”到列表中

6. 找到“Linking\Other Linker Flags”项,并添加“-lxml2”到列表中

在需要调用GDataXML的代码文件头部,加入:

#import “GDataXMLNode.h”

TouchXML

1. 从https://github.com/TouchCode/TouchXML下载最新TouchXML源码

2. 解压后,将其中的Sources目录下的文件和目录都拖到项目中

3. 选中项目,选中“Build Settings”标签页

4. 将Build Settings页中,顶部的“Basic”标签切换到“All”

5. 找到“Paths\Header Search Paths”项,并添加“/usr/include/libxml2”到列表中

6. 找到“Linking\Other Linker Flags”项,并添加“-lxml2”到列表中

在需要调用TouchXML的代码文件头部,加入:

#import “TouchXML.h”

TBXML

1. 从http://www.tbxml.co.uk/TBXML/TBXML_Free.html下载最新TBXML源码

2. 解压后,将其中的TBXML.h, TBXML.m, NSDataAdditions.h和NSDataAddtions.m四个文件拖到项目中

3. 添加对libz.dylib类库的应用

在需要调用TBXML的代码文件头部,加入:

#import “TBXML.h”

使用说明
GDataXML

读取XML文件,并解析成为DOM文档对象示例:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@”test” ofType:@”xml”];

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];

NSError *error;

GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];

if (doc == nil) { return nil; }

NSLog(@”%@”, doc.rootElement);

[doc release];

[xmlData release];

浏览数: 次 星期五, 02月 10th, 2012 未分类 没有评论

isMemberOfClass的使用举例isKindOfClass的应用举例

isMemberOfClass方法是来确定对象是否是某一个类的成员。在下一个任务中,我们使用这个方法来验证一个特定的对象是否是一个特定的类成员


isKindOfClass 我们也可以使用isKindOfClass来检查一个对象是否是一个类的成员。isMemberOfClass和isKindOfClass之间区别是: 我们可以使用isKindOfClass来确定一个对象是否是一个类的成员,或者是派生自该类的成员。

例如:我们已经成NSObject派生了自己的类,isMemberOfClass不能检测任何的类都是基于NSObject类这一事实,而isKindOfClass可以。

浏览数: 次 星期日, 02月 5th, 2012 未分类 没有评论