2009-12-10 165 views
1

我想在我看來兩點之間劃線如何可能。?如何在兩點之間畫線?

編輯:雅thax.i已得到解決方案。線條繪製完美。我想用不同的點繪製多條線。我使用for循環和每個rotaion我通過開始和結束points.but只有最後一點繪製。如何解決這個問題?

回答

4

QuartzDemo應用程序有很好的例子說明如何使用CoreGraphics,包括線和貝塞爾曲線。 download here

查看示例代碼中的QuartzLineDrawing.m。您可以找到一些很好的例子有:-)

6

您需要使用一些CoreGraphics中的功能:

// get the current context 
CGContextRef context = UIGraphicsGetCurrentContext(); 

// set the stroke color and width 
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); 
CGContextSetLineWidth(context, 2.0); 

// move to your first point 
CGContextMoveToPoint(context, 10.0, 10.0); 

// add a line to your second point 
CGContextAddLineToPoint(context, 50.0, 10.0); 

// tell the context to draw the stroked line 
CGContextStrokePath(context); 

這個例子將畫一條水平線白線厚度爲2蘋果一些很棒的示例代碼和教程,包括QuartzDemo教程:http://developer.apple.com/iPhone/library/samplecode/QuartzDemo/index.html

+0

我想你的代碼,但不斷收到錯誤:「無效的情況下」,並沒有什麼拉!我錯過了什麼? – adranale 2010-11-01 19:24:55

0

由於這是09'的答案,我不知道如何更新鏈接和代碼在這裏爲任何人在11'。

的鏈接,石英演示是:http://developer.apple.com/library/ios/#samplecode/QuartzDemo/Introduction/Intro.html

,我用它來畫多行的代碼是:

//Drawing lines 

    // Set the color that we want to use to draw the line 
[ [ UIColor brownColor] set]; 

    //Get the current graphics context (pen) 
CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    // Set the width for the line 
CGContextSetLineWidth(currentContext, 
         5.0f); 

    // Start the line at this point 
CGContextMoveToPoint(currentContext, 
        20.0f, 
        20.0f); 
    // And end it at this point 
CGContextAddLineToPoint(currentContext, 
         100.0f, 
         100.0f); 

    // Extend the line to another point 
CGContextAddLineToPoint(currentContext, 
         300.0f, 
         100.0f); 


    //Use the context's current color to draw the line 
CGContextStrokePath(currentContext); 

我建議你閱讀Graphics and Animation on iOS: A Beginner's Guide to Core Graphics and Core Animation by Vandad Nahavandipoor。它主要是在圖形上,而不是動畫。如果您感興趣,我建議查看他的動畫視頻。 http://www.youtube.com/watch?v=ybMFPB-Gbsw&feature=player_embedded它們被稱爲iOS中使用塊對象的動畫第I部分和第II部分。據說在某些時候應該有更多的視頻。但是這些視頻隨書一起提供。

就是這樣。

0
-(IBAction)btnRoutePathClicked:(id)sender 
{ 
    [self.mapView removeAnnotation:point]; 

    [self.mapView removeOverlay:polyline]; 

    [self.mapView reloadInputViews]; 



    MKCoordinateSpan span = MKCoordinateSpanMake(1.0, 1.0); 
    MKCoordinateRegion region = MKCoordinateRegionMake(currentLocation.coordinate, span); 

    [self.mapView setRegion:region]; 

    [self.mapView setCenterCoordinate:currentLocation.coordinate animated:YES]; 

    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true",[NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude],[NSString stringWithFormat:@"22.45,72.4545"]]; 

    //http://maps.googleapis.com/maps/api/directions/json?origin=51.194400,4.475816&destination=50.941278,6.958281&sensor=true 

    NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 


    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 

     NSError *error = nil; 
     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 

     NSArray *routes = [result objectForKey:@"routes"]; 


     if ([routes count]==0) 
     { 
      NSLog(@"Routs:=>%@",routes); 

     } 
     else 
     { 
      NSDictionary *firstRoute = [routes objectAtIndex:0]; 

      NSDictionary *leg = [[firstRoute objectForKey:@"legs"] objectAtIndex:0]; 

      NSDictionary *end_location = [leg objectForKey:@"end_location"]; 

      double latitudes = [[end_location objectForKey:@"lat"] doubleValue]; 
      double longitudes = [[end_location objectForKey:@"lng"] doubleValue]; 

      CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitudes, longitudes); 

      point = [[MKPointAnnotation alloc] init]; 
      point.coordinate = coordinate; 
      point.title = [leg objectForKey:@"end_address"]; 

      [self.mapView addAnnotation:point]; 

      NSDictionary *route = [routes lastObject]; 
      if (route) 
      { 
       NSString *overviewPolyline = [[route objectForKey: @"overview_polyline"] objectForKey:@"points"]; 

       NSMutableArray *_path = [self decodePolyLine:overviewPolyline]; 

       NSInteger numberOfSteps = _path.count; 

       CLLocationCoordinate2D coordinates[numberOfSteps]; 

       for (NSInteger index = 0; index < numberOfSteps; index++) 
       { 
        CLLocation *location = [_path objectAtIndex:index]; 
        CLLocationCoordinate2D coordinate = location.coordinate; 
        coordinates[index] = coordinate; 
       } 

       polyline = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps]; 

       [self.mapView addOverlay:polyline]; 
      } 
     } 
    }]; 

} 
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr 
{ 
    NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]]; 
    [encoded appendString:encodedStr]; 
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\" 
           options:NSLiteralSearch 
            range:NSMakeRange(0, [encoded length])]; 
    NSInteger len = [encoded length]; 
    NSInteger index = 0; 
    NSMutableArray *array = [[NSMutableArray alloc] init]; 
    NSInteger lat=0; 
    NSInteger lng=0; 
    while (index < len) 
    { 
     NSInteger b; 
     NSInteger shift = 0; 
     NSInteger result = 0; 
     do 
     { 
      b = [encoded characterAtIndex:index++] - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 

     NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1)); 
     lat += dlat; 
     shift = 0; 
     result = 0; 
     do 
     { 
      b = [encoded characterAtIndex:index++] - 63; 
      result |= (b & 0x1f) << shift; 
      shift += 5; 
     } while (b >= 0x20); 

     NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1)); 
     lng += dlng; 
     NSNumber *latitudes = [[NSNumber alloc] initWithFloat:lat * 1e-5]; 
     NSNumber *longitudes = [[NSNumber alloc] initWithFloat:lng * 1e-5]; 

     CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitudes floatValue] longitude:[longitudes floatValue]]; 
     [array addObject:location]; 
    } 
    return array; 
} 

- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay{ 

    MKPolylineRenderer *polylineView = [[MKPolylineRenderer alloc] initWithPolyline:overlay]; 
    polylineView.strokeColor = [UIColor redColor]; 
    polylineView.lineWidth = 4.0; 
    polylineView.alpha = 0.5; 
    return polylineView; 
} 
0
#pragma mark - Mapview Delegate Method 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    MKPinAnnotationView *pin = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"id"]; 

    if (!pin && ![annotation isKindOfClass:[MKUserLocation class]]) 
    { 

     pin = [[MKPinAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"id"] ; 
     pin.pinTintColor=[UIColor blueColor]; 
     pin.canShowCallout = true; 
    } 
    else 
    { 

     if (pin == nil) 
     { 
      pin = [[MKPinAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"id"] ; 
     } 
     else 
     { 
      pin.annotation = annotation; 
     } 

     pin.pinTintColor=[UIColor grayColor]; 

     UIView *notationView=[[UIView alloc]init]; 
     notationView.frame=CGRectMake(0, 0, 320, 300); 
     notationView.backgroundColor = [UIColor grayColor]; 

     UILabel *lbl=[[UILabel alloc]init]; 
     lbl.frame=CGRectMake(5, 5, 300, 25); 
     [email protected]"Current Location"; 
     lbl.textColor=[UIColor whiteColor]; 
     [notationView addSubview:lbl]; 

     UIImageView *img=[[UIImageView alloc]init]; 
     img.frame=CGRectMake(0, 0, 50,50); 

     img.image=[UIImage imageNamed:@"ios.png"]; 

     // pin.leftCalloutAccessoryView = notationView; 
     // pin.rightCalloutAccessoryView = img; 

     //pin.detailCalloutAccessoryView=customView; 

     pin.animatesDrop = true; 

     pin.canShowCallout = true; 

    } 

    return pin; 
} 
+0

您可以添加一些文字來解釋解決方案中的代碼嗎? – Kmeixner 2016-05-20 13:28:05

0
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) 
{ 
    let CurrentLogitude = String(format: "%.8f", newLocation.coordinate.longitude) 
    //print(CurrentLogitude) 
    let CurrentLatitude = String(format: "%.8f", newLocation.coordinate.latitude) 
    // print(CurrentLatitude) 
    //[self.locationManager stopUpdatingLocation]; 
} 
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) 
{ 
} 
func locationManager(manager: CLLocationManager, 
    didChangeAuthorizationStatus status: CLAuthorizationStatus) 
{ 
     var shouldIAllow = false 
     var locationStatus :String 

     switch status 
     { 
      case CLAuthorizationStatus.Restricted: 
       locationStatus = "Restricted Access to location" 
      case CLAuthorizationStatus.Denied: 
       locationStatus = "User denied access to location" 
      case CLAuthorizationStatus.NotDetermined: 
       locationStatus = "Status not determined" 
      default: 
       locationStatus = "Allowed to location Access" 
       shouldIAllow = true 
     } 

     NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) 
     if (shouldIAllow == true) 
     { 
      NSLog("Location to Allowed") 
      // Start location services 
      locationManager.startUpdatingLocation() 
     } else { 
      NSLog("Denied access: \(locationStatus)") 
     } 
} 


func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? 
{ 
    let pin = MKAnnotationView(annotation: annotation, reuseIdentifier: "locationpin") 
    pin.image = UIImage(named: "locationpin.png") 

    let notationView: UIView = UIView() 
    notationView.frame = CGRectMake(0, 0, 400, 300) 
    notationView.backgroundColor = UIColor.grayColor() 
    pin.leftCalloutAccessoryView = notationView 
    pin.canShowCallout = true 
    return pin 
}