how to draw line between two points?

前端 未结 6 560
难免孤独
难免孤独 2021-01-03 14:43

i want to draw line between two points in my view how it possible.?

Edit:ya thax.i have got solution. Line draw perfectly.I want to draw multiple line with different

相关标签:
6条回答
  • 2021-01-03 15:17

    Since this is 09' answers and whatnot I figure I update the link and code here for anyone looking in 11'.

    The link for the Quartz Demo is: http://developer.apple.com/library/ios/#samplecode/QuartzDemo/Introduction/Intro.html

    and the code I use to draw multiple lines is:

       //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);
    

    I recommend reading Graphics and Animation on iOS: A Beginner's Guide to Core Graphics and Core Animation by Vandad Nahavandipoor. It's mostly on graphics than animation though. I recommend checking out his videos on animation if your interested. http://www.youtube.com/watch?v=ybMFPB-Gbsw&feature=player_embedded They're called Animations in iOS using Block Objects Part I and II. Supposedly there are supposed to be more videos at some point. But the videos go with the book.

    That's it.

    0 讨论(0)
  • 2021-01-03 15:17
    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
    }
    
    0 讨论(0)
  • 2021-01-03 15:18
    #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;
    }
    
    0 讨论(0)
  • 2021-01-03 15:23

    You need to use a few CoreGraphics functions:

    // 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);
    

    This example would draw a horizontal white line with a thickness of 2. Apple has some great sample code and tutorials including the QuartzDemo tutorial: http://developer.apple.com/iPhone/library/samplecode/QuartzDemo/index.html.

    0 讨论(0)
  • 2021-01-03 15:30

    The QuartzDemo application has great examples of how to use CoreGraphics, including lines and bezier curves. download here

    Take a look at QuartzLineDrawing.m in the sample code. You'll be able to find some great examples there :-)

    0 讨论(0)
  • 2021-01-03 15:35
    -(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 讨论(0)
提交回复
热议问题