我需要从MKMapView
(UIView
)创建UIImage
。但是我不想覆盖整个UIView
,但仅覆盖其中的一部分,确切地说,我希望图像为 200x200 像素,图像的中心应该是地图上的用户位置。
我创建了一个UIView
类别并尝试了以下内容,但它行不通。我得到图像,但用户位置不是图像的中心。我在做什么错?
- (UIImage*)captureView:(MKMapView *)map
{
CGPoint newCenter = [map convertCoordinate:map.userLocation.coordinate toPointToView:map];
CGRect rect = CGRectMake(newCenter.x-100.0, newCenter.y-100.0, 200.0, 200.0);
NSLog(@"%f,@%f",rect.origin.x,rect.origin.y);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
目前,图像总是从左上角开始,尽管当我NSLog
时我的坐标是正确的。
您应该将转换应用于上下文,以将您想要的内容移至正确的位置之前。
CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);