我有世界地图的图像.svg
我加载到UIWebView
。 (我使用了svg格式和UIWebView,因为图像太大而无法加载到UIImageView中)
我想在这张地图上放置一堆具有固定位置的图钉。
例如,如果我在巴西放置了一个图钉,则无论我滚动或缩放该图钉,该图钉都必须始终保留在巴西。UIWebView
你怎么能做到这一点?目前滚动不是问题,只有缩放是问题
NSString *path = [[NSBundle mainBundle] pathForResource:@"map" ofType:@"svg"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
[_webView loadRequest:request];
_webView.scalesPageToFit = YES;
_webView.delegate = self;
UIButton *but = [[UIButton alloc] initWithFrame:CGRectMake(100, 400, 30, 30)];
[but setBackgroundColor:[UIColor blackColor]];
[_webView.scrollView addSubview:but];
EDIT正如 @dymv 使用 ScrollView 的委托方法所建议的,我们可以更改按钮的大小,但存在问题:
如何在许多按钮中重用此代码?
EDIT2:
我解决了与许多按钮相关的问题,但现在看来我无法将引脚固定在同一点上。
显然,图钉的坐标会根据缩放而变化,但问题是视觉上图钉移动到它应该在的位置太多。
例如,如上所述,如果我在巴西海岸放置一个图钉,当我缩小时,图钉会越过海洋,并且不会留在海岸上。
这确实是一个问题,因为引脚太多,最终结果会很糟糕
-(void)webViewDidFinishLoad:(UIWebView *)webView {
CGPoint primo = CGPointMake(100, 100);
for (int i = 0; i<36; i++) {
UIButton *bu = [[UIButton alloc] initWithFrame:CGRectMake(primo.x, primo.y, 10, 18)];
[bu setBackgroundImage:[UIImage imageNamed:@"pin"] forState:UIControlStateNormal];
[bu addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchUpInside];
[_webView.scrollView addSubview:bu];
bu.tag = i;
[arrayOfPoint addObject:[NSValue valueWithCGPoint:bu.center]];
[arrayOfRect addObject:[NSValue valueWithCGRect:bu.frame]];
primo.x = primo.x + 20;
primo.y = primo.y + 10;
}
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
CGFloat scale = scrollView.zoomScale;
for (UIView *button in scrollView.subviews) {
if ([button isMemberOfClass:[UIButton class]]) {
int i = button.tag;
NSValue *newValue = [arrayOfRect objectAtIndex:i];
CGRect newFrame = [newValue CGRectValue];
button.frame = CGRectMake(CGRectGetMinX(newFrame) * scale,
CGRectGetMinY(newFrame) * scale,
CGRectGetWidth(newFrame),
CGRectGetHeight(newFrame));
}
}
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
for (UIView *button in scrollView.subviews) {
if ([button isKindOfClass:[UIButton class]]) {
int tag = button.tag;
CGRect rectPre = button.frame;
[arrayOfRect replaceObjectAtIndex:tag withObject:[NSValue valueWithCGRect:rectPre]];
}
}
}
SOLVED:
解决定位问题只需改变这个方法:
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
CGFloat scale = scrollView.zoomScale;
for (UIView *button in scrollView.subviews) {
if ([button isMemberOfClass:[UIButton class]]) {
int i = button.tag;
NSValue *newValue = [arrayOfRect objectAtIndex:i];
CGRect newFrame = [newValue CGRectValue];
button.frame = CGRectMake(CGRectGetMinX(newFrame) * scale,
CGRectGetMinY(newFrame) * scale,
CGRectGetWidth(newFrame) * scale, //add *scale
CGRectGetHeight(newFrame) * scale); // add *scale
}
}
}