quantka quantka - 1 year ago 72
iOS Question

CALayer border width resizes when zooming

In the header file:

@property (strong,nonatomic) IBOutlet UIView *zoomView;

In the m file, I initialize the zoomView with some size, color and border width:

- (void)viewDidLoad
[super viewDidLoad];

//initialize the zoom rectangle
[zoomView.layer setBorderColor: [[UIColor orangeColor] CGColor]];
[zoomView.layer setBorderWidth: 4.0];
[zoomView.layer setFrame: CGRectMake(zoomView.layer.frame.origin.x, zoomView.layer.frame.origin.y, 100, 200)];

Then on some user actions, particularly pinching, I call this code:

-(void)redrawBox {
[zoomView.layer setBorderWidth: 4.0];
[zoomView.layer setNeedsLayout];

Unfortunately the border width varies wildly. When the box is zoomed out, the border width increases proportionately, which ends up looking really bad. I've double checked that this code is called and the border width is properly set (it works just fine if I set the width to 0, then the box disappears), but it seems that a border width of 4.0 renders VERY differently at different zoom levels.

How can I set the border width to be constant regardless of how the rectangle is zoomed? Thanks!

Answer Source

I've realized the problem is that the transform is still set on the box, so it zooms the border. The solution I came up with is:

-(void)redrawBox {
    //set the border width again so that the width doesn't change with zooming
   CGRect currentFrame = zoomView.layer.frame;
    zoomView.transform = CGAffineTransformIdentity;
    [zoomView.layer setBorderWidth: 4.0];
    [zoomView.layer setFrame: CGRectMake(currentFrame.origin.x, currentFrame.origin.y, currentFrame.size.width, currentFrame.size.height)];

This redraws the box from scratch at the right size but without a transform set so the border is actually 4 points.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download