Search code examples
iosipadinterface-buildercgrect

Transparent rect in view controller


I want to achieve an affect similar to a round html form with a transparent background similar to the image below (not the mouseover text, just the rectangle in the background, and have it have an opacity).

I do not know how to do this and I've toyed around with CGRect but I can't even get them to come up. I'm using the tab navigation based template for the iPad.

Could you please point me to some resources that could get me started with CGRect?

enter image description here


Solution

  • Note I'm going to make the assumption you're after the grey background rectangle behind the two form fields. Not the blue border around the email field. I'm assuming you want to achieve something similar to this:

    iPad Screenshot

    You need to create custom UIView subclass that either contains or sits directly behind your form fields and buttons. Depending on the complexity of your gradient and corner radius you can achieve a similar effect one of two ways.

    1. Using CALayer's cornerRadius and borderColor and borderWidth

    A simple implementation of this view could be:

    #import "RoundedView.h"
    #import <QuartzCore/QuartzCore.h>
    
    @implementation RoundedView
    
    - (id)initWithFrame:(CGRect)frame
    {
      if ((self = [super initWithFrame:frame])) {
        self.backgroundColor = [UIColor grayColor];
        self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        self.layer.cornerRadius = 10;
      }
      return self;
    }
    
    @end
    

    2. Overriding drawRect: to draw rounded corners

    You'll be using UIBezierPath to draw a rect with rounded corners, fill it and stroke it.

    @implementation DrawnBackgroundView
    
    - (id)initWithFrame:(CGRect)frame
    {
      if ((self = [super initWithFrame:frame])) {
        self.backgroundColor = [UIColor clearColor];
      }
      return self;
    }
    
    
    - (void)drawRect:(CGRect)rect
    {
      CGFloat lineWidth = 2;
      CGFloat selfWidth = self.bounds.size.width - (lineWidth * 2);
      CGFloat selfHeight = self.bounds.size.height - (lineWidth * 2);
    
      UIColor* lightGray = [UIColor colorWithRed: 0.84 green: 0.84 blue: 0.84 alpha: 1];
    
      UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(lineWidth, lineWidth, selfWidth, selfHeight) cornerRadius: 10];
      [lightGray setFill];
      [roundedRectanglePath fill];
    
      [lightGray setStroke];
      roundedRectanglePath.lineWidth = lineWidth;
      [roundedRectanglePath stroke];
    }
    
    @end
    

    The screen shot above is taken from a quick demo project that is available on GitHub.