ios开发小技巧(转)

时间:2021-10-09 00:31:20

1.通过下面方式可以获取图片的像素颜色点:
- (void*)getImageData:(UIImage*)image
{
    void* imageData;
    if (imageData == NULL) 
        imageData = malloc(4 * image.size.width * image.size.height);
    
    CGColorSpaceRef cref = CGColorSpaceCreateDeviceRGB();
    CGContextRef gc = CGBitmapContextCreate(imageData,
                                            image.size.width,image.size.height,
                                            8,image.size.width*4,
                                            cref,kCGImageAlphaPremultipliedFirst);
    CGColorSpaceRelease(cref);
    UIGraphicsPushContext(gc);
    
    [image drawAtPoint:CGPointMake(0.0f, 0.0f)];
    
    UIGraphicsPopContext();
    CGContextRelease(gc);
    return imageData;
}

2.UILabel和UITextField的小应用
    UILabel *LY_Label = [[UILabel alloc] initWithFrame:CGRectMake(60, 180, 60, 30)];
    [self.view addSubview:LY_Label];
    LY_Label.backgroundColor = [UIColor clearColor];
    LY_Label.text = @"密   码";
    LY_Label.font= [UIFont fontWithName:@"zapfino" size:(15.0f)]; //字体设置
   [[LY_Label layer] setBorderWidth:2.0f];  //边框设置

UITextField *LY_Text = [[UITextField alloc] initWithFrame:CGRectMake(143, 180, 80, 30) ];
    [self.view addSubview:LY_Text];
    LY_Text.backgroundColor = [UIColor whiteColor];
    [LY_Text setBorderStyle:UITextBorderStyleLine];             //边框设置
    LY_Text.placeholder = @"password";                          //默认显示的字
    LY_Text.font = [UIFont fontWithName:@"helvetica" size:12];  //字体和大小设置
    LY_Text.textColor = [UIColor redColor];                     //设置字体的颜色
    LY_Text.clearButtonMode = UITextFieldViewModeWhileEditing;  //清空功能x
    LY_Text.returnKeyType = UIReturnKeyDone;                    //键盘有done

LY_Text.secureTextEntry = YES;                              //密码输入时

[LY_Text  becomeFirstResponder];                    //自动弹出软键盘

LY_Text.delegate = self;                                    //托管

3.navigatrionbar 导航条设置颜色

UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320,44)];

bar.tintColor = [UIColor blackColor];

UINavigationItem *barItem = [[UINavigationItem alloc] initWithTitle:@""];

[bar setItems:[NSArray arrayWithObjects:barItem,nil]];

[baseView addSubview:bar];

4.AnnotationView的一些操作

-
(MKAnnotationView
*)mapView:(MKMapView
*)aMapView
viewForAnnotation:(id <MKAnnotation>)annotation
{ if(![annotation
isKindOfClass:[MyAnnotation class]])
//
Don't mess
user location return
nil;
MKAnnotationView *annotationView
=
[aMapView
dequeueReusableAnnotationViewWithIdentifier:@"spot"]; if(!annotationView) {
annotationView = [[MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:@"spot"];
annotationView.rightCalloutAccessoryView = [UIButton
buttonWithType:UIButtonTypeDetailDisclosure]; [(UIButton
*)annotationView.rightCalloutAccessoryView
addTarget:self action:@selector(openSpot:)
forControlEvents:UIControlEventTouchUpInside];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
annotationView.centerOffset = CGPointMake(7,-15);
annotationView.calloutOffset = CGPointMake(-8,0);
} // Setup annotation
view annotationView.image
=
[UIImage
imageNamed:@"pinYellow.png"];
//
Or
whatever return
annotationView;
}

- (MKAnnotationView
*)mapView:(MKMapView *)mapView
viewForAnnotation:(id
)annotation {

if (annotation == mapView.userLocation) {

return nil;

}

MKPinAnnotationView *pinView = [[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"Pin"] autorelease];

pinView.pinColor = MKPinAnnotationColorRed;

pinView.canShowCallout = YES;

pinView.rightCalloutAccessoryView = [UIButtonbuttonWithType:UIButtonTypeDetailDisclosure];

pinView.animatesDrop = YES;

UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

button.frame = CGRectMake(0, 0, 25, 25);

[button setTitle:[NSStringstringWithFormat:@"%f,%f",self.touchCordinate.latitude,self.touchCordinate.longitude]forState:UIControlStateNormal];

pinView.rightCalloutAccessoryView = button;

return pinView;

}

5.iphone开发----计算MKMapView的zoomlevel
计算地图的zoom level,如下:

#define MERCATOR_RADIUS 85445659.44705395

- (int)getZoomLevel:(MKMapView*)_mapView {

return 21-round(log2(_mapView.region.span.longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * _mapView.bounds.size.width)));

}

我们可以写一个MKMapView的委托方法打印出zoom level

- (void)mapView:(MKMapView *)_mapView regionDidChangeAnimated:(BOOL)animated {

NSLog(@"zoom level %d", [self getZoomLevel:_mapView]);

}

结果范围在1-19之间,1就是全球地图。
6.在固定位置画一定大小的圈

UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc]initWithTarget:self

action:@selector(longPress:)];

lpress.minimumPressDuration = 0.3;//按0.5秒响应longPress方法

lpress.allowableMovement = 10.0;

//给MKMapView加上长按事件

[self._mapView addGestureRecognizer:lpress];//mapView是MKMapView的实例

[lpress release];

}

return self;

}

- (void)longPress:(UIGestureRecognizer*)gestureRecognizer {

if (gestureRecognizer.state == UIGestureRecognizerStateBegan){  //这个状态判断很重要

//坐标转换

CGPoint touchPoint = [gestureRecognizer locationInView:self._mapView];

CLLocationCoordinate2D touchMapCoordinate =

[self._mapView convertPoint:touchPoint toCoordinateFromView:self._mapView];

self.touchCoordinate = touchMapCoordinate;

NSLog(@"location:%f,%f",touchMapCoordinate.latitude,touchMapCoordinate.longitude);

if (nil != self.newAnnotation) {

[self._mapView removeAnnotation:self.newAnnotation];

}

self.newAnnotation = [Annotation annotationWithCoordinate:self.touchCoordinate];

self.newAnnotation.title = [NSStringstringWithFormat:@"%f,%f",self.touchCoordinate.latitude,self.touchCoordinate.longitude];

if (nil != self.newAnnotation) {

[self._mapView addAnnotation:self.newAnnotation];

[self locationcircle:self.touchCoordinate radius:[circleScaleText.text doubleValue]];

}

//这里的touchMapCoordinate.latitude和touchMapCoordinate.longitude就是需要的经纬度,

//NSString *url = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&region=sh&language=zh-CN", touchMapCoordinate.latitude, touchMapCoordinate.longitude];

//[NSThread detachNewThreadSelector:@selector(loadMapDetailByUrl:) toTarget:self withObject:url];

}

}

//在鼠标点击位置添加固定大小的圈

-(void)locationcircle:(CLLocationCoordinate2D)coordinate radius:(CLLocationDistance)circleradius {

if (nil != self.locCircle) {

[self._mapView removeOverlay:locCircle];

}

locCircle = [MKCircle circleWithCenterCoordinate:coordinate radius:circleradius];

[self._mapView addOverlay:locCircle];

}

//改变位置圈的大小

- (IBAction)changecircleScale{

[self dismissWithClickedButtonIndex:0 animated:YES];

[self locationcircle:self.touchCoordinate radius:[circleScaleText.text doubleValue]];

}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {

if (annotation == mapView.userLocation) {

return nil;

}

MKPinAnnotationView *pinView = [[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"Pin"] autorelease];

pinView.pinColor = MKPinAnnotationColorRed;

pinView.canShowCallout = YES;

pinView.rightCalloutAccessoryView = [UIButtonbuttonWithType:UIButtonTypeDetailDisclosure];

pinView.animatesDrop = YES;

UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

button.frame = CGRectMake(0, 0, 25, 25);

[button setTitle:[NSStringstringWithFormat:@"%f,%f",self.touchCoordinate.latitude,self.touchCoordinate.longitude]forState:UIControlStateNormal];

pinView.rightCalloutAccessoryView = button;

return pinView;

}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay

{

if ([overlay isKindOfClass:[MKCircle class]])

{

MKCircleView* circleView = [[[MKCircleView alloc] initWithOverlay:overlay]autorelease];

circleView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2];

circleView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];

circleView.lineWidth = 3.0;

return circleView;

}

return nil;

}

- (int)getZoomLevel:(MKMapView*)mapView {

return 21-round(log2(mapView.region.span.longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * mapView.bounds.size.width)));

}

//一个MKMapView的委托方法控制zoomlevel

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {

//NSLog(@"zoom level %d", [self getZoomLevel:_mapView]);

}

- (void)setFrame:(CGRect)rect {

//[super setFrame:CGRectMake((320-rect.size.width)/2, 130, rect.size.width, 150)];

//self.center = CGPointMake(320/2, 480/2);

[super setFrame:CGRectMake(0, 20, 320, 460)];

}

- (void)layoutSubviews {

CGFloat buttonTop;

for (UIView *view in self.subviews) {

if ([[[view class] description] isEqualToString:@"UIThreePartButton"]) {

view.frame = CGRectMake(view.frame.origin.x,

self.bounds.size.height - view.frame.size.height - 15,

view.frame.size.width,

view.frame.size.height);

buttonTop = view.frame.origin.y+200;

}

}

buttonTop -= 40;

NSLog(@"buttontop:%f",buttonTop);

circleLb.frame = CGRectMake(12, 50, 80, 30);

circleScaleText.frame = CGRectMake(100, 52, 150, 25);

changeBtn.frame = CGRectMake(260, 50, 40, 30);

}

7.mapView 定位当前位置使用CLLocationManager

#import "UserLoactionTestViewController.h"

@implementation UserLoactionTestViewController

- (void)loadView {

[super loadView];

mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 10, 320, 400)];

[mapView setDelegate:self];

[mapView setMapType:MKMapTypeStandard];

[self.view addSubview:mapView];

[mapView release];

mapView.showsUserLocation=YES;

CLLocationManager *locationManager = [[CLLocationManager alloc] init];//创建位置管理器

locationManager.delegate=self;//设置代理

locationManager.desiredAccuracy=kCLLocationAccuracyBest;//指定需要的精度级别

//locationManager.distanceFilter=1000.0f;//设置距离筛选器

[locationManager startUpdatingLocation];//启动位置管理器

MKCoordinateSpan theSpan;

//地图的范围 越小越精确

theSpan.latitudeDelta= 0.05f;

theSpan.longitudeDelta=0.05f;

MKCoordinateRegion theRegion;

CLLocationCoordinate2D cr  = locationManager.location.coordinate;

theRegion.center = cr; //[[locationManager location] coordinate];

theRegion.span = theSpan;

[mapView setRegion:theRegion];

//NSLog(@"%f  %f",mapView.userLocation.location.coordinate.latitude,

//   mapView.userLocation.location.coordinate.longitude);

}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

//NSLog(@"dfdfdfd");

mapView.region = MKCoordinateRegionMake(newLocation.coordinate, MKCoordinateSpanMake(0.005f, 0.005f));

[manager stopUpdatingHeading];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

- (void)viewDidUnload {

}

- (void)dealloc {

[super dealloc];

}

@end

8.手指控制放大缩小(转的 没自己测验过,以后有需求的时候可以参考下)

CGRect scrollFrame = CGRectMake(20,90,280,280);

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];

scrollView.minimumZoomScale = 0.5;

scrollView.maximumZoomScale = 2.0;

scrollView.delegate = self;

UIImage *bigImage = [UIImage imageNamed:@"appleLogo.jpg"];

largeImageView = [[UIImageView alloc] initWithImage:bigImage];

[scrollView addSubview:largeImageView];

scrollView.contentSize = largeImageView.frame.size; //important!

[self.view addSubview:scrollView];

[scrollView release];

9.长按操作(转) (没尝试过,看到了,先收着)(跟上面地图的长按有点相似)
            UILongPressGestureRecognizer *longpressGesture = [[UILongPressGestureRecognizer alloc] init];
            longpressGesture.minimumPressDuration = 1;
            longpressGesture.cancelsTouchesInView = NO;
            [longpressGesture addTarget:self action:@selector(buttonLongPressed:)];
            [boxButton addGestureRecognizer:longpressGesture];
            [longpressGesture release];
11 resizeImage
http://www.iphonedevsdk.com/forum/iphone-sdk-development/7307-resizing-photo-new-uiimage.html
12 在mapview的特定位置上添加图片

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);

MapAnnotation *annotation = [[MapAnnotationalloc] initWithcoordiante:coordinate];

[map_view addAnnotations: annotation];

[annotation release];

3.写文件的一种方法

NSData *dataToWrite = [s dataUsingEncoding: NSUTF8StringEncoding];

NSFileHandle* outputFile = [NSFileHandle fileHandleForWritingAtPath:Log_FilePath];

[outputFile seekToEndOfFile]; //可以在文件的末尾继续写下去

[outputFile writeData:dataToWrite];

实现pushViewController的自定义动画效果
CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = @"cube";
transition.subtype = kCATransitionFromRight;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];

DemoViewController *demoViewController = 
[[DemoViewController alloc]
initWithNibName:@"DemoViewController"
bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController: demoViewController animated:YES];

[demoViewController release];

简单介绍:.type  设置了主要的页面切换显示形式 cube 等
 .subtype 设置了页面的旋转  左右上下 :~)