如何在两点之间画线?

时间:2009-12-10 05:36:19

标签: iphone

我想在我看来两点之间画线如何可能。?

编辑:ya thax.i已经解决了。线条绘制完美。我想用不同的点绘制多条线。我正在使用for循环和每个旋转我通过起点和终点。但是只绘制了最后一点如何解决这个问题?

6 个答案:

答案 0 :(得分: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的水平白线.Apple有一些很棒的示例代码和教程,包括QuartzDemo教程:http://developer.apple.com/iPhone/library/samplecode/QuartzDemo/index.html

答案 1 :(得分:4)

QuartzDemo应用程序提供了有关如何使用CoreGraphics的很好示例,包括直线和贝塞尔曲线。 download here

在示例代码中查看QuartzLineDrawing.m。你可以在那里找到一些很好的例子: - )

答案 2 :(得分:0)

因为这是09'的答案,所以我想知道我在这里为11'的任何人更新链接和代码。

Quartz Demo的链接是: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中使用Block Objects 第一部分和第二部分称为动画。据说在某些时候应该有更多的视频。但视频随书一起出现。

就是这样。

答案 3 :(得分: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;
}

答案 4 :(得分: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);
        lbl.text=@"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;
}

答案 5 :(得分: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
}