低质量MKMapView动态生成的图像

时间:2011-08-09 19:39:33

标签: iphone objective-c mkmapview quartz-graphics

在任何人指出this post之前,我已经尝试过了,但这对我不起作用。我正在尝试生成MKMapView的黑白快照。然而,iPhone 4的质量非常低。这是我的代码。有人有什么建议吗?

- (void)mapSnapShotWithMapView:(MKMapView *)_mapView {
    CGSize s = CGSizeMake(_mapView.bounds.size.width, _mapView.bounds.size.height);
    UIGraphicsBeginImageContextWithOptions(s, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[_mapView layer] renderInContext:ctx];
    UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    ctx = CGBitmapContextCreate(nil, s.width, s.height, 8, s.width, colorSpace, kCGImageAlphaNone);
    CGContextSetShouldAntialias(ctx, YES);
    CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);

    CGContextDrawImage(ctx, CGRectMake(0, 0, s.width, s.height), thumb.CGImage);
    CGImageRef bwImage = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];
    [imageView setImage:[UIImage imageWithCGImage:bwImage]];
    CGImageRelease(bwImage);
    [self.view addSubView:imageView];
    [imageView release];
}

1 个答案:

答案 0 :(得分:1)

感谢this post,我想通了。它没有使用iPhone的原始分辨率,即使0.0f作为UIGraphicsBeginImageContextWithOptions的最后一个参数应该这样做。无论如何,这是更新的代码:

- (void)mapSnapShotWithMapView:(MKMapView *)_mapView {
  CGSize s = _mapView.bounds.size;
  CGFloat scale = 1.0;
  if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    scale = [[UIScreen mainScreen] scale];
    s = CGSizeApplyAffineTransform(s, CGAffineTransformMakeScale(scale, scale));
  }

  UIGraphicsBeginImageContextWithOptions(s, NO, 1.0f);
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CGContextScaleCTM(ctx, scale, scale);
  [[_mapView layer] renderInContext:ctx];
  UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
  ctx = CGBitmapContextCreate(nil, s.width, s.height, 8, s.width, colorSpace, kCGImageAlphaNone);
  CGContextSetShouldAntialias(ctx, YES);
  CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);

  CGContextDrawImage(ctx, CGRectMake(0, 0, s.width, s.height), thumb.CGImage);
  CGImageRef bwImage = CGBitmapContextCreateImage(ctx);
  CGContextRelease(ctx);
  CGColorSpaceRelease(colorSpace);

  UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width/2, s.height/2)];
  [imageView setImage:[UIImage imageWithCGImage:bwImage]];
  CGImageRelease(bwImage);
  [self.view addSubview:imageView];
  [imageView release];
}