Brinde ideas sobre cómo recortar UIImage
en forma oval o en forma de círculo. Por favor guíame.¿Cómo recortar UIImage en forma oval o en forma de círculo?
Respuesta
#import <QuartzCore/QuartzCore.h>
CALayer *imageLayer = YourImageview.layer;
[imageLayer setCornerRadius:5];
[imageLayer setBorderWidth:1];
[imageLayer setMasksToBounds:YES];
al aumentar el radio será más de ida y capaces.
Mientras que la imagen es un cuadrado, se puede obtener un círculo perfecto, tomando la mitad de la anchura que el radio de la esquina:
[imageView.layer setCornerRadius:imageView.frame.size.width/2];
También es necesario añadir
[imageView.layer setMasksToBounds:YES];
Echa un vistazo CGImageCreateWithMask
. Crea una máscara de tu forma ovalada y luego aplícala a la imagen.
cómo separar de forma ovalada en mi imagen? por favor me ayude – ram
debe consultar This ...
// 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)); //oval logic goes here
// 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];
Después de una búsqueda larga Encontré la forma correcta de rodear la imagen
Descargar el archivo de archivo de ayuda de la dirección URL http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
#import "UIImage+RoundedCorner.h"
#import "UIImage+Resize.h"
siguientes líneas se utilizan para cambiar el tamaño de la imagen y convertir a redondear con un radio
UIImage *mask = [UIImage imageNamed:@"mask.jpg"];
mask = [mask resizedImage:CGSizeMake(47, 47) interpolationQuality:kCGInterpolationHigh ];
mask = [mask roundedCornerImage:23.5 borderSize:1];
empecé a buscar en esto un par de semanas atrás. Probé todas las sugerencias aquí, ninguna de las cuales funcionó bien. En la gran tradición de RTFM, fui y leí la documentación de Apple en Quartz 2D Programming y se me ocurrió esto. Pruébelo y dígame cómo va.
El código podría modificarse bastante fácilmente para recortar en una elipse, o en cualquier otra forma definida por una ruta.
Asegúrate de incluir Quartz 2D en tu proyecto.
#include <math.h>
+ (UIImage*)circularScaleAndCropImage:(UIImage*)image frame:(CGRect)frame {
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
//Create the bitmap graphics context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(frame.size.width, frame.size.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
//Get the width and heights
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat rectWidth = frame.size.width;
CGFloat rectHeight = frame.size.height;
//Calculate the scale factor
CGFloat scaleFactorX = rectWidth/imageWidth;
CGFloat scaleFactorY = rectHeight/imageHeight;
//Calculate the centre of the circle
CGFloat imageCentreX = rectWidth/2;
CGFloat imageCentreY = rectHeight/2;
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
CGFloat radius = rectWidth/2;
CGContextBeginPath (context);
CGContextAddArc (context, imageCentreX, imageCentreY, radius, 0, 2*M_PI, 0);
CGContextClosePath (context);
CGContextClip (context);
//Set the SCALE factor for the graphics context
//All future draw calls will be scaled by this factor
CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
// Draw the IMAGE
CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
[image drawInRect:myRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Incluir el siguiente código en su clase UIView en sustitución de "monk2.png" con su propio nombre de la imagen.
- (void)drawRect:(CGRect)rect {
UIImage *originalImage = [UIImage imageNamed:[NSString stringWithFormat:@"monk2.png"]];
CGFloat oImageWidth = originalImage.size.width;
CGFloat oImageHeight = originalImage.size.height;
// Draw the original image at the origin
CGRect oRect = CGRectMake(0, 0, oImageWidth, oImageHeight);
[originalImage drawInRect:oRect];
// Set the newRect to half the size of the original image
CGRect newRect = CGRectMake(0, 0, oImageWidth/2, oImageHeight/2);
UIImage *newImage = [self circularScaleAndCropImage:originalImage frame:newRect];
CGFloat nImageWidth = newImage.size.width;
CGFloat nImageHeight = newImage.size.height;
//Draw the scaled and cropped image
CGRect thisRect = CGRectMake(oImageWidth+10, 0, nImageWidth, nImageHeight);
[newImage drawInRect:thisRect];
}
Si solo necesitas un círculo perfecto, cambiar la forma del UIImageView podría ser útil. sólo tiene que añadir el marco QuartzCore a su proyecto y añadir estas líneas de código en alguna parte del ciclo de vida antes de que aparezca el imageView:
#import <QuartzCore/QuartzCore.h>
.
.
.
//to crop your UIImageView to show only a circle
yourImageView.layer.cornerRadius = yourImageView.frame.size.width/2;
yourImageView.clipsToBounds = YES;
Esta respuesta dinámica es una respuesta mucho mejor que la elegida. –
Para realizar una imagen RoundShape
Paso 1: en el archivo .h
@property (strong, nonatomic) IBOutlet UIImageView *songImage;
Paso 2: en.archivo m
- (void)viewDidLoad
{
self.songImage.layer.cornerRadius = self.songImage.frame.size.width/2;
self.songImage.clipsToBounds = YES;
//To give the Border and Border color of imageview
self.songImage.layer.borderWidth = 1.0f;
self.songImage.layer.borderColor = [UIColor colorWithRed:249/255.0f green:117/255.0f blue:44/255.0f alpha:1.0f].CGColor;
}
O para SWIFT
cell.songImage.layer.cornerRadius = cell.songImage.frame.size.width/2;
cell.songImage.clipsToBounds = true
//To give the Border and Border color of imageview
cell.songImage.layer.borderWidth = 1.0
cell.songImage.layer.borderColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0).CGColor
Para tener imageView en forma oval no es difícil.
Usted puede hacer lo siguiente
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:yourImageView.bounds];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = path.CGPath;
yourImage.layer.mask = maskLayer;
Si el rect pasado a bezierPathWithOvalInRect es la Plaza de la imagen se recortará al círculo.
Código Swift
let path = UIBezierPath(ovalIn: yourImageView.bounds)
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
yourImage.layer.mask = maskLayer
esto funciona para mí. –
¿puedo usar uiview en lugar de uiimage para que sea ovalado? –
cómo recortar la imagen de forma ovalada para el objetivo c? –
SWIFT
var vwImage = UIImageView(image: UIImage(named: "Btn_PinIt_Normal.png"))
vwImage.frame = CGRectMake(0, 0, 100, 100)
vwImage.layer.cornerRadius = vwImage.frame.size.width/2
SWIFT 3 respuesta viene de @Mohammad Sadiq
let path = UIBezierPath.init(ovalIn: workingImgaeView.bounds)
let maskLayer = CAShapeLayer(layer: layer)
maskLayer.path = path.cgPath
workingImgaeView.layer.mask = maskLayer
- 1. UIImage en un círculo
- 2. Cómo recortar el UIImage?
- 3. Recortar un UIImage en iPhone
- 4. Recortar o enmascarar una imagen en un círculo
- 5. Gradiente Oval en Android
- 6. Recortar UIImage como un camscanner
- 7. tamaño del nodo con forma de círculo =
- 8. Remodelación de moneda ruidosa en forma de círculo
- 9. La mejor forma de recortar espacios en una cadena
- 10. cómo colocar 12 círculos en forma pareja en un círculo grande
- 11. Máscara de recorte en forma de sector circular con Path.addArc?
- 12. ¿Cómo comprobar nulo o falso en Scala de forma concisa?
- 13. ¿Cómo puedo transformar/animar una forma personalizada en un círculo? CANVAS JS
- 14. Dibujar una forma anulada en SVG
- 15. ¿Alguna forma de obtener un UIImage en caché de mi directorio 'Documentos'?
- 16. ¿Cuál es la forma canónica de recortar una cadena en Ruby sin crear una nueva cadena?
- 17. ¿Cómo puedo configurar el fondo de mi forma en xml?
- 18. ¿Cómo mostrar o ver datos encriptados en forma encriptada?
- 19. iOS - Organizar subvistas en forma circular
- 20. ¿Cómo recorto una imagen basada en una forma irregular?
- 21. Pirámide: ¿forma simple o deformada?
- 22. cómo recortar "a b c" en "abc"
- 23. Deshacer personalizado en forma diseñada o control de usuario
- 24. Eliminar archivos o carpetas de forma recursiva en Windows cmd
- 25. Cómo recortar una imagen en iOS
- 26. Recargar o borrar datos en forma existente en Symfony2.1
- 27. PHP GD - Forma de cultivo
- 28. recortar una imagen ampliada en ImageView dentro de scrollView
- 29. Cómo dibujar un UIImage o directamente en -drawRect :?
- 30. Cómo hacer un círculo en una cuadrícula?
Te faltan '[setMasksToBounds imageLayer: SÍ];' :) –
Sí, usted tiene que utilizar la sugerencia de Andrés para recortar la imagen a la forma de la ImageView – Shailesh
Mientras que la imagen es un cuadrado, se puede obtener una perfecto círculo mediante la adopción de la mitad de la anchura que el radio de la esquina: [imageView.layer setCornerRadius: imageView.frame.size.width/2]; self.imageView.layer.masksToBounds = YES; –