简体   繁体   中英

How do I crop a MKMapView (or any UIView) into a custom shape?

I'm trying to size an MKMapView in the following way:

顶部为弧形的地图视图

Elements should be able to appear behind the arc at the top, so it appears that the view is not square. I know this should be possible with CALayer, but perhaps someone has done it before?

This should be quite possible if you put your MKMapView within a UIView, then apply a mask to that.

Here's a very (!) basic example:

在此处输入图片说明

All I've done is put my map in a UIView called "mapContainer" and added a mask to it using this:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    CGRect rect = CGRectInset(self.view.frame, 70, 70);
    UIView* newView = [[UIView alloc] initWithFrame:rect];
    newView.layer.cornerRadius = 55.0;
    newView.backgroundColor = [UIColor redColor];

    self.mapContainer.layer.mask = newView.layer;
}

And you could add a border to it...

在此处输入图片说明

..with a few more lines...

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    CGRect rect = CGRectInset(self.view.frame, 70, 70);
    UIView* newView = [[UIView alloc] initWithFrame:rect];
    newView.layer.cornerRadius = 55.0;
    newView.backgroundColor = [UIColor redColor];

    UIView* borderView = [[UIView alloc] initWithFrame:rect];
    borderView.backgroundColor = [UIColor clearColor];
    borderView.layer.cornerRadius = 55.0;
    borderView.layer.borderWidth = 3.0;
    borderView.layer.borderColor = [[UIColor redColor] CGColor];
    [self.mapContainer addSubview:borderView];
    [self.mapContainer bringSubviewToFront:borderView];

    self.mapContainer.layer.mask = newView.layer;
}

I hope this points you in the right direction.

Unlike Apple Maps.

;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM