views:

4843

answers:

5

How can i take an UIImage and give it a black border? (iphone)

tnx

+2  A: 

You could manipulate the image itself, but a much better way is to simply add a UIView that contains the UIImageView, and change the background to black. Then set the size of that container view to a little bit larger than the UIImageView.

Kendall Helmstetter Gelner
Is it going to work with a different size of images that change on the fly?The UIImageView will change all the time, and the UIView?p.s. Manipulate the image itself will be great.
donodare
You'd have to adjust the frame of the containing view along with the image - you could save off the center properties for both views, adjust the image size, adjust the container size, and then re-set center properties for both.
Kendall Helmstetter Gelner
This is exactly the way I did it as opposed to stroking the path with CG. just seemed easier.
Corey Floyd
+2  A: 

You can't add a border, but this would work for the same effect. You could also make the UIView called blackBG in this example into a UIImageView with a border image and a blank middle, and then you'd have a custom image border instead of just black.

UIView *blackBG = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];

blackBG.backgroundColor = [UIColor blackColor];

UIImageView *myPicture = [[UIImageView alloc] initWithImage:
                          [UIImage imageNamed: @"myPicture.jpg"]];

int borderWidth = 10;

myPicture.frame = CGRectMake(borderWidth,
                             borderWidth,
                             blackBG.frame.size.width-borderWidth*2,
                             blackBG.frame.size.height-borderWidth*2)];

[blackBG addSubview: myPicture];
Andrew Johnson
+7  A: 

You can do this by creating a new image (also answered in your other posting of this question):

- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
  CGSize size = [source size];
  UIGraphicsBeginImageContext(size);
  CGRect rect = CGRectMake(0, 0, size.width, size.height);
  [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0); 
  CGContextStrokeRect(context, rect);
  UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return testImg;
}

This code will produce a pink border around the image. However if you are going to just display the border then use the layer of the UIImageView and set its border.

Marcus S. Zarra
+12  A: 

With OS > 3.0 you can do this:

//you need this import
#import <QuartzCore/QuartzCore.h>

[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
mclin
A: 

how the two imageviews will be collapsed

jyothi