tomar tomadas profesionales plus fotos con como iphone ios objective-c uiimageview uiimage

iphone - tomadas - ¿Cómo puedo tomar un UIImage y darle un borde negro?



iphone 6 fotos tomadas (15)

¿Cómo puedo establecer el borde de un UIImage ?


// necesitas importar

QuartzCore/QuartzCore.h

y luego para ImageView en el borde

[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]]; [imageView.layer setBorderWidth: 2.0]; [imageView.layer setCornerRadius: 5.0];


Con OS> 3.0 puedes hacer esto:

//you need this import #import <QuartzCore/QuartzCore.h> [imageView.layer setBorderColor: [[UIColor blackColor] CGColor]]; [imageView.layer setBorderWidth: 2.0];


En Swift 3, esta es la forma en que lo haces con el UIImage mismo:

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


Esta función te devolverá la imagen con borde negro. Intenta esto ... espero que esto te ayude

- (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; }


No puede agregar un borde, pero esto funcionaría para el mismo efecto. También podría hacer que UIView llamara blackBG en este ejemplo a UIImageView con una imagen de borde y un centro en blanco, y luego tendría un borde de imagen personalizado en lugar de solo negro.

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];


Otra forma es hacerlo directamente desde el diseñador.

Seleccione su imagen y vaya a "Mostrar el inspector de identidad".

Aquí puede agregar manualmente " Atributos de tiempo de ejecución definidos por el usuario" :

layer.borderColor layer.borderWidth



Para aquellos que buscan una solución plug-and-play en UIImage, escribí la respuesta de CodyMace como una extensión.

Uso: 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 } }


Puede agregar bordes a UIImageView y luego cambiar el tamaño de UIimageView de acuerdo con el tamaño de la imagen:

#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;

Asegúrese de establecer el origen de la imageView en el centro


Puede hacer esto creando una nueva imagen (también respondida en su otra publicación de esta pregunta):

- (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; }

Este código producirá un borde rosado alrededor de la imagen. Sin embargo, si solo va a mostrar el borde, use la capa del UIImageView y establezca su borde.


Puede manipular la imagen en sí, pero una forma mucho mejor es simplemente agregar un UIView que contenga el UIImageView y cambiar el fondo a negro. Luego, configure el tamaño de la vista del contenedor a un poco más grande que el UIImageView.


Si conoce las dimensiones de su imagen, entonces agregar un borde a la capa de UIImageView es la mejor solución AFAIK. De hecho, puedes simplemente configurar tu imagen como x, y, image.size.width, image.size.height

En caso de que tengas una ImageView de un tamaño fijo con imágenes cargadas dinámicamente que están siendo redimensionadas (o escaladas a AspectFit), entonces tu objetivo es redimensionar la imagen a la nueva imagen redimensionada.

La forma más corta de hacer esto:

// 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)];

Pero para usar AVMakeRectWithAspectRatioInsideRect, debe agregar esto

#import <AVFoundation/AVFoundation.h>

importar el extracto a su archivo y también incluir el marco AVFoundation en su proyecto (viene incluido con el SDK).


Uso este método para agregar un borde fuera de la imagen . Puede personalizar el ancho del borde en boderWidth constante.

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; }


todas estas respuestas funcionan bien PERO agregan un rect a una imagen. Supongamos que tiene una forma (en mi caso una mariposa) y desea agregar un borde (un borde rojo):

necesitamos dos pasos: 1) tomar la imagen, convertirla a CGImage, pasarla a una función para dibujar fuera de pantalla en un contexto usando CoreGraphics, y devolverle una nueva CGImage

2) convertir a uiimage y dibujar:

// 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];

}

Agregué una mariposa normal y una mariposa más grande con borde rojo.


#import <QuartzCore/CALayer.h> UIImageView *imageView = [UIImageView alloc]init]; imageView.layer.masksToBounds = YES; imageView.layer.borderColor = [UIColor blackColor].CGColor; imageView.layer.borderWidth = 1;

Este código se puede usar para agregar el UIImageView vista UIImageView .


imageView_ProfileImage.layer.cornerRadius =10.0f; imageView_ProfileImage.layer.borderColor = [[UIColor blackColor] CGColor]; imageView_ProfileImage.layer.borderWidth =.4f; imageView_ProfileImage.layer.masksToBounds = YES;