1

Can anybody please explain which is the right way to draw a dotted rectangular border around UILabel which can be resized and movable, I have searched a lot, found 2 ways:

First is,

_border = [CAShapeLayer layer];

_border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;

_border.fillColor = nil;

_border.lineDashPattern = @[@4, @2];

[self.layer addSublayer:_border];

And in your layoutsubviews, put this:

_border.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
_border.frame = self.bounds;

Second is, It could be done by drawing a border around NSAttributed String in UILabel

Issues:

  1. Since for resizing the UILabel based on user touch,already I am changing its size touch methods,again I need to write bunch of lines to resize the border layer
  2. Didn't get the approach to draw border on away from text not on text itself.

Can anybody please help in sorting the optimized approach.

Jack
  • 13,571
  • 6
  • 76
  • 98
user1740045
  • 191
  • 2
  • 10

1 Answers1

1

The following code is much better to understand

   CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
        [shapeLayer setBounds:shapeRect];
        [shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
        [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
        [shapeLayer setLineWidth:2.0f];
        [shapeLayer setLineJoin:kCALineJoinRound];
        [shapeLayer setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
        [NSNumber numberWithInt:5],
          nil]];

for more check this OR you can simply put a image for UITextfeild and stretch it. OR try

[yourView.layer setBorderWidth:5.0];
[yourView.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"DotedImage.png"]]
Community
  • 1
  • 1
Muruganandham K
  • 5,271
  • 5
  • 34
  • 62
  • 1
    Using modern syntax the last line becomes more readable: `[shapeLayer setLineDashPattern:@[ @5, @5 ]];` – DarkDust Nov 26 '13 at 13:45
  • Yes Image is an option but again its frame has to be adjusted as per the UILabel (Resizable,Movable),Similarly we can do this thru CAShapeLayer. if we draw the Dotted Border through CAShapeLayer its border also has to be adjusted as per UILabel its size and position but thats not working(In Touch Method where the UILabel frame is set,we set the frame of layer as well but border layer not moving along UILabel). Also which one is better or there is any other good approach – user1740045 Nov 26 '13 at 13:52
  • @user1740045 can you came across `CATextLayer`? – Muruganandham K Nov 26 '13 at 14:12