Iphone, how to add outline on an image? - iphone

I want to add outline on an image, do you have any idea?
Note: I don't need the border of imageview, not imageview.layer.borderColor nor image.layer.borderWidth;

Try this :
- (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;
}
source : http://www.icodesnip.com/snippet/objective-c/add-image-border-to-uiimage

This may not be a very clean way but may work and is simple.
//Make a UIView instance with required coords and size
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(...)];
//Set a backgroundColor, that will be the color of your border
view.backgroundColor = [UIColor ...];
// Make a UIImageView instance with the frame just leaving enough
// space around for the border.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(...)];
imageView.image = yourImage;
// Add the imageView to the view.
[view addSubview:imageView];
[imageView release];
// Release view accordingly after adding to some other view.
The sizes of the view and imageView will what give your image a border.
eg. (0, 0, 10, 10) -> view frame
(1, 1, 8, 8) -> imageView frame
This will give border of "1" to the image.

Related

iPhone:-simplest way to crop image of desired shape and size

i am trying to crop image according to my desire....for my cinemagram type app.....and use it in my application
i have tried a lot of options but none of tham is...usefull for me
i read answers on stack over flow but of no use
plzz help me out
image = [UIImage imageNamed:#"images2.jpg"];
imageView = [[UIImageView alloc] initWithImage:image];
CGSize size = [image size];
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];
thanks
Here is the exact code to resize your image to desired size
CGSize itemSize = CGSizeMake(320,480); // give any size you want to give
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[myimage drawInRect:imageRect];
myimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Now my image is of your desired size
Please find the code below to the crop the image.
// Create the image from a png file
UIImage *image = [UIImage imageNamed:#"prgBinary.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Get size of current image
CGSize size = [image size];
// Frame location in view to show original image
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];
// Create rectangle that represents a cropped image
// from the middle of the existing image
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2));
// Create bitmap image from original image data,
// using rectangle to specify desired crop area
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// Create and show the new image from bitmap data
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(0, 200, (size.width / 2), (size.height / 2))];
[[self view] addSubview:imageView];
[imageView release];
Referred from How to Crop an Image
I think this is the most simple way:
CGRect rect = CGRectMake(0.0, 0.0, 320.0, 430.0);
CGImageRef tempImage = CGImageCreateWithImageInRect([originalImage CGImage], rect);
UIImage *newImage = [UIImage imageWithCGImage:tempImage];
CGImageRelease(tempImage);
But don't forget to clear imageOrientation BEFORE cropping, otherwise you will get rotated image after cropping:
-(UIImage *)normalizeImage:(UIImage *)raw {
if (raw.imageOrientation == UIImageOrientationUp) return raw;
UIGraphicsBeginImageContextWithOptions(raw.size, NO, raw.scale);
[raw drawInRect:(CGRect){0, 0, raw.size}];
UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return normalizedImage;
}
Here is a class using Dinesh's answer to get a square thumbnail of an image
class func returnSquareCroppedImage(theImage:UIImage)->UIImage{
var mySize:CGFloat = 100.0
var imageRect:CGRect
if theImage.size.width > theImage.size.height {
mySize = theImage.size.height
let xAdjust = 0-((theImage.size.width - theImage.size.height)/2)
imageRect = CGRectMake(xAdjust, 0, theImage.size.width, theImage.size.height)
}else{
mySize = theImage.size.width
let yAdjust = 0-((theImage.size.height - theImage.size.width)/2)
imageRect = CGRectMake(0, yAdjust, theImage.size.width, theImage.size.height)
}
UIGraphicsBeginImageContext(CGSizeMake(mySize, mySize))
theImage.drawInRect(imageRect)
let returnImage = UIGraphicsGetImageFromCurrentImageContext()
return returnImage
}

UIImageView round corner has white background

The rounded corner has white background.
I followed other SO answers but don't know why i'm getting this whites
Bellow is the code.
UIView* testView = [[[UIView alloc] initWithFrame: self.animationView.bounds] autorelease];
UIImageView* testImageView = [[[UIImageView alloc] initWithImage:backImage] autorelease];
[testView addSubview: testImageView];
testImageView.backgroundColor = [UIColor clearColor];
CALayer* layer = [testView layer];
bool prev = layer.masksToBounds;
layer.masksToBounds = YES;
layer.cornerRadius = 30;
testView.clipsToBounds = YES;
UIImage* image = [UIImage captureView: testView];
//this image has the white regions in the four corners.
// when seen on iphone photo album
+ (UIImage*)captureView:(UIView*)view
{
CGSize size = view.bounds.size;
CGContextRef context = CreateARGBBitmapContext(size);
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[view.layer renderInContext: context];
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);
CGContextRelease(context);
return img;
}
Add [testImageView setClipsToBounds:YES].
It might be that you have to set testImageView.opaque = NO.

check on images displayed in UIScrollview

Hi i am new to IPhone development.
I am creating UIImageViews programmatically on button click. but every time i click the button they get drawn at the same place. the image drawing code is as follows.
- (IBAction)Button
{
arrayOfImages = [[NSMutableArray alloc]init];
float x = 15.0,y = 15.0, width = 100.0, height = 100;
CGRect frame = CGRectMake(x, y, width, height);
int i= 0;
if ([shape isEqualToString:#"Rectangle"])
{
UIGraphicsBeginImageContext(frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGRect main =CGRectMake(x, y, 70.0, 30.0);
CGContextFillRect(context, main);
CGRect topSeat1 = CGRectMake(15.0, 0.0, 15.0, 13.0);
CGRect topSeat2 = CGRectMake(42.5, 0.0, 15.0, 13.0);
CGRect topSeat3 = CGRectMake(70.0, 0.0, 15.0, 13.0);
CGRect leftSeat = CGRectMake(0.0, 22.5, 13.0, 15.0);
CGRect rightSeat = CGRectMake(87.0, 22.5, 13.0, 15.0);
[[UIColor redColor]set];
//UIRectFill(main);
UIRectFill(topSeat1);
UIRectFill(topSeat2);
UIRectFill(topSeat3);
UIRectFill(leftSeat);
UIRectFill(rightSeat);
UIRectFrame(main);
[[UIColor blackColor]set];
UIRectFrame(topSeat1);
UIRectFrame(topSeat2);
UIRectFrame(topSeat3);
UIRectFrame(leftSeat);
UIRectFrame(rightSeat);
UIImage * images = [[UIImage alloc]init];
images = UIGraphicsGetImageFromCurrentImageContext();
UIImageView* myImage=[[UIImageView alloc]initWithFrame:frame];
[myImage setImage:images];
myImage.tag= i;
i++;
UIGraphicsEndImageContext();
[self.view addSubview:myImage];
[arrayOfImages addObject:myImage];
[myImage setUserInteractionEnabled:YES];
}
}
all i want is that if i click the button it should check that if there is already UIIMAgeView drawn at that place then it draws the UIIMageView a bit away from it.
I would appreciate if u help me with some code.
use a variable to store the click count of the button, then use the variable to adjust the place of your view
or you may ask for the superview for subviews and compare the frame of the subview with your image view
for (UIView *subview in self.view.subviews) {
if (/* compare subview.frame with myImage.frame */) {
/* update myImage.frame */
break;
}
}

Setting a UIImage border

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?
There's some solutions in this question: How can i take an UIImage and give it a black border?
#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
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;
}

How can I take an UIImage and give it a black border?

How can I set the border of a UIImage?
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];
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.
#import <QuartzCore/CALayer.h>
UIImageView *imageView = [UIImageView alloc]init];
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor = [UIColor blackColor].CGColor;
imageView.layer.borderWidth = 1;
This code can be used for adding UIImageView view border.
imageView_ProfileImage.layer.cornerRadius =10.0f;
imageView_ProfileImage.layer.borderColor = [[UIColor blackColor] CGColor];
imageView_ProfileImage.layer.borderWidth =.4f;
imageView_ProfileImage.layer.masksToBounds = YES;
If you know the dimensions of your image, then adding a border to the UIImageView's layer is the best solution AFAIK. Infact, you can simply setFrame your imageView to x,y,image.size.width,image.size.height
In case you have an ImageView of a fixed size with dynamically loaded images which are getting resized (or scaled to AspectFit), then your aim is to resize the imageview to the new resized image.
The shortest way to do this:
// containerView is my UIImageView
containerView.layer.borderWidth = 7;
containerView.layer.borderColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0].CGColor;
// this is the key command
[containerView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, containerView.frame)];
But to use the AVMakeRectWithAspectRatioInsideRect, you need to add this
#import <AVFoundation/AVFoundation.h>
import statement to your file and also include the AVFoundation framework in your project (comes bundled with the SDK).
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];
all these answers work fine BUT add a rect to an image.
Suppose You have a shape (in my case a butterfly) and You want to add a border (a red border):
we need two steps:
1) take the image, convert to CGImage, pass to a function to draw offscreen in a context using CoreGraphics, and give back a new CGImage
2) convert to uiimage back and draw:
// remember to release object!
+ (CGImageRef)createResizedCGImage:(CGImageRef)image toWidth:(int)width
andHeight:(int)height
{
// create context, keeping original image properties
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width,
height,
8
4 * width,
colorspace,
kCGImageAlphaPremultipliedFirst
);
CGColorSpaceRelease(colorspace);
if(context == NULL)
return nil;
// draw image to context (resizing it)
CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
CGSize offset = CGSizeMake(2,2);
CGFloat blur = 4;
CGColorRef color = [UIColor redColor].CGColor;
CGContextSetShadowWithColor ( context, offset, blur, color);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imgRef;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect frame = CGRectMake(0,0,160, 122);
UIImage * img = [UIImage imageNamed:#"butterfly"]; // take low res OR high res, but frame should be the low-res one.
imgV = [[UIImageView alloc]initWithFrame:frame];
[imgV setImage: img];
imgV.center = self.view.center;
[self.view addSubview: imgV];
frame.size.width = frame.size.width * 1.3;
frame.size.height = frame.size.height* 1.3;
CGImageRef cgImage =[ViewController createResizedCGImage:[img CGImage] toWidth:frame.size.width andHeight: frame.size.height ];
imgV2 = [[UIImageView alloc]initWithFrame:frame];
[imgV2 setImage: [UIImage imageWithCGImage:cgImage] ];
// release:
if (cgImage) CGImageRelease(cgImage);
[self.view addSubview: imgV2];
}
I added a normal butterfly and a red-bordered bigger butterfly.
You can add border to the UIImageView, and then change the size of the UIimageView according to the image size:
#import <QuartzCore/QuartzCore.h>
// adding border to the imageView
[imageView.layer setBorderColor: [[UIColor whiteColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
// resize the imageView to fit the image size
CGSize size = [image size];
float factor = size.width / self.frame.size.width;
if (factor < size.height / self.frame.size.height) {
factor = size.height / self.frame.size.height;
}
CGRect rect = CGRectMake(0, 0, size.width/factor, size.height/factor);
imageView.frame = rect;
Make sure you to set the origin of the imageView to the center
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.
Another way is to do directly from designer.
Select your image and go under "Show the Identity inspector".
Here you can manually add "User Defined Runtime Attributes":
layer.borderColor
layer.borderWidth
//you need to import
QuartzCore/QuartzCore.h
& then for ImageView in border
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];
[imageView.layer setCornerRadius: 5.0];
This function will return you image with black border try this.. hope this will help you
- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
CGSize size = CGSizeMake(image.size.width,image.size.height);
UIGraphicsBeginImageContext(size);
CGPoint thumbPoint = CGPointMake(0,0);
[image drawAtPoint:thumbPoint];
UIGraphicsBeginImageContext(size);
CGImageRef imgRef = blackBorderImage.CGImage;
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPoint starredPoint = CGPointMake(0, 0);
[imageCopy drawAtPoint:starredPoint];
UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageC;
}
In Swift 3 here's how you do it to the UIImage itself:
let size = CGSize(width: image.size.width, height: image.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image?.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.imageView.image = newImage
For those looking for a plug-and-play solution on UIImage, I wrote CodyMace's answer as an extension.
Usage: let outlined = UIImage(named: "something")?.outline()
extension UIImage {
func outline() -> UIImage? {
let size = CGSize(width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
self.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
I have created a class which adds a border to imageView h. Use this class instead of UIImageView.I have given a padding of 4. You can give as per your wish.
class UIBorderImageView: UIView {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.White()
self.layer.borderColor = UIColor.GreyMedium().cgColor
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 4.0
self.layer.masksToBounds = true
self.setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUpViews(){
self.addSubview(imageView)
self.addConstraintsWithFormat(format: "H:|-4-[v0]-4-|", views: imageView)
self.addConstraintsWithFormat(format: "V:|-4-[v0]-4-|", views: imageView)
}
func configureImageViewWith(image:UIImage){
self.imageview.image = image
}}
I use this method to add a border outside the image. You can customise the border width in boderWidth constant.
Swift 3
func addBorderToImage(image : UIImage) -> UIImage {
let bgImage = image.cgImage
let initialWidth = (bgImage?.width)!
let initialHeight = (bgImage?.height)!
let borderWidth = Int(Double(initialWidth) * 0.10);
let width = initialWidth + borderWidth * 2
let height = initialHeight + borderWidth * 2
let data = malloc(width * height * 4)
let context = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: (bgImage?.colorSpace)!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue);
context?.draw(bgImage!, in: CGRect(x: CGFloat(borderWidth), y: CGFloat(borderWidth), width: CGFloat(initialWidth), height: CGFloat(initialHeight)))
context?.setStrokeColor(UIColor.white.cgColor)
context?.setLineWidth(CGFloat(borderWidth))
context?.move(to: CGPoint(x: 0, y: 0))
context?.addLine(to: CGPoint(x: 0, y: height))
context?.addLine(to: CGPoint(x: width, y: height))
context?.addLine(to: CGPoint(x: width, y: 0))
context?.addLine(to: CGPoint(x: 0, y: 0))
context?.strokePath()
let cgImage = context?.makeImage()
let uiImage = UIImage(cgImage: cgImage!)
free(data)
return uiImage;
}