5

Is there a way to set borders to a UIImage. I know how to set it for UIImageView, but my problem is the UIImage that I load up in a UIImageview wont be of the same size or aspect ratio as the UIImageView. Hence Ive kept the UIImageView mode to aspect fit. Giving a border to UIImageView now would border the entire UIImageView rather than just the UIImage, and that doesn't look good when the UIImage is not of the same size or aspect ratio as the UIV.

Help?

Rupert
  • 51
  • 1
  • 1
  • 2

3 Answers3

3

There's some solutions in this question: How can i take an UIImage and give it a black border?

Community
  • 1
  • 1
Matt Williamson
  • 39,165
  • 10
  • 64
  • 72
  • Two problems here. That other question is about rendering a UIImage directly, not using a UIImageView. Also, the best solution places the border around the frame of the UIImageView, not the aspect fitted image within the UIImageView. – Matt Connolly Oct 18 '11 at 10:07
  • Actually, the other question is similar, it's just the popular answer there that doesn't help here. – Matt Connolly Oct 18 '11 at 10:13
1
#import <QuartzCore/CALayer.h>


UIImageView *imageView = [UIImageView alloc]init];
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor = [UIColor blackColor].CGColor;
imageView.layer.borderWidth = 1;
imageView.layer.cornerRadius = 10; //optional
Sameera R.
  • 4,384
  • 2
  • 36
  • 53
0
image with border

+(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,(255/255.f),(255/255.f),(255/255.f), 1.0);
    CGContextStrokeRect(context, rect);
    UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return testImg;
}
user2155906
  • 149
  • 5