Transparent Ring in iOS

2019-02-20 04:25发布

问题:

I have a circle avatar on my view. I make it like this:

self.imageView.layer.cornerRadius = 75;
self.imageView.layer.masksToBounds = YES;
self.imageView.layer.borderWidth = 1;
self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;

But I want transparent 2px ring between avatar and white border. I can't draw a white circle on the background, because the avatar can move and ring position will be lost. I have the idea to stroke path using

CGContextSetBlendMode(context, kCGBlendModeClear);

after assigning the layer, but I don't catch how exactly do it. Appreciate for your help.

回答1:

that question seems to be a lack-of-imagination issue only.


here is a quick solution for the problem:

in the Interface Builder, you need to add a container view and that view holds the avatar image view; it is the raw picture of how it look on my screen the view in the editor:

that is the relationship between the two views in the view hiearchy: the container view is the superview of the avatar image view:

after adding the related outlets (call them _containerView and _avatarImageView) to the class and conntected them to the views; we also can add this little snippet to our code:

[_containerView setBackgroundColor:[UIColor clearColor]];
[_containerView.layer setCornerRadius:MIN(_containerView.bounds.size.width, _containerView.bounds.size.height) / 2.0];
[_containerView.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[_containerView.layer setBorderWidth:4.0];

[_avatarImageView.layer setCornerRadius:MIN(_avatarImageView.bounds.size.width, _avatarImageView.bounds.size.height) / 2.0];
[_avatarImageView.layer setMasksToBounds:TRUE];

and after running the project on the simulator or a real device, violá, the transparent ring appears between the image and the border:


NOTE: the actual size of the transparent ring depends on how much smaller the avatar than the container view, which holds it. Important! I do not know who the girl is, please don't ask me about her phone number.