在地图中对UIView进行子类化以绘制线条

时间:2011-05-18 02:34:27

标签: iphone uiview ios4 uiscrollview subclass

我有一个显示自定义地图的应用。我使用CATiledView来显示地图。

我希望能够在地图顶部绘制一条路线。为此,我创建了一个UIView,然后在我添加这样的平铺层后将其添加到scrollView:

- (void)displayTiledImageNamed:(NSString *)imageName size:(CGSize)imageSize
{
    // clear the previous imageView
    [imageView removeFromSuperview];
    [imageView release];
    imageView = nil;
    [linesView removeFromSuperview];
    [linesView release];
    linesView = nil;

    // reset our zoomScale to 1.0 before doing any further calculations
    self.zoomScale = 1.0;

    // make a new TilingView for the new image
    imageView = [[TilingView alloc] initWithImageName:imageName size:imageSize];
    linesView = [[LinesView alloc]initWithImageName:imageName size:imageSize];

    linesView.backgroundColor = [UIColor clearColor];
    [self addSubview:imageView];
    [self addSubview:linesView];
    [self configureForImageSize:imageSize];


}

问题是,我在linesView中创建的行未正确缩放。

很难描述,但正在创建的线被缩放,好像它是在设备上绘制的,而不是在地图上绘制的。请参阅以下代码:

#import "LinesView.h"


@implementation LinesView
@synthesize imageName;


- (id)initWithImageName:(NSString *)name size:(CGSize)size
{
    if ((self = [super initWithFrame:CGRectMake(0, 0, size.width, size.height)])) {
        self.imageName = name;

    }

    return self;
}
- (void)dealloc
{
    [super dealloc];
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
    CGContextSetLineWidth(context, 20.0);
    CGContextMoveToPoint(context, 1.0f, 220.0f);
    CGContextAddLineToPoint(context, 340.0f, 80);
    CGContextStrokePath(context);
}

@end

我已经尝试将代码放在tilingView的drawRect方法中绘制线条并且它完美地工作。线宽相对于地图是20px。在linesView中,线条相对于设备显示为20px宽,并相对于滚动视图定位。

对不起,我正在尽力描述这个问题......

1 个答案:

答案 0 :(得分:0)

想出这个 - 我将linesView添加到tilingView而不是scrollView,如下所示:

- (void)displayTiledImageNamed:(NSString *)imageName size:(CGSize)imageSize
{
    // clear the previous imageView
    [imageView removeFromSuperview];
    [imageView release];
    imageView = nil;
    [linesView removeFromSuperview];
    [linesView release];
    linesView = nil;

    // reset our zoomScale to 1.0 before doing any further calculations
    self.zoomScale = 1.0;

    // make a new TilingView for the new image
    imageView = [[TilingView alloc] initWithImageName:imageName size:imageSize];
    linesView = [[LinesView alloc]initWithImageName:imageName size:imageSize];

    linesView.backgroundColor = [UIColor clearColor];
    [self addSubview:imageView];
    [imageView addSubview:linesView];
    [self configureForImageSize:imageSize];


}