我有一张图片,我想根据任何视图的帧进行裁剪。例如;
我真的找不到解决方案。我已经搜索了2天。
已编辑
感谢@Ajharul伊斯兰教和@Bence Pattogato。这两个答案都起作用。
@Ajharul Islam解决方案的快速版本。
func images(byCroppingImage image: UIImage?, to size: CGSize) -> UIImage? {
// not equivalent to image.size (which depends on the imageOrientation)!
let refWidth = (image?.cgImage?.width)!
let refHeight = (image?.cgImage?.height)!
let x = (Double(refWidth) - Double(size.width)) / 2
let y = (Double(refHeight) - Double(size.height)) / 2
let cropRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)
let imageRef = image?.cgImage!.cropping(to: cropRect) as! CGImage
var cropped: UIImage? = nil
if let imageRefs = image?.cgImage!.cropping(to: cropRect) {
cropped = UIImage(cgImage: imageRefs, scale: 0.0, orientation: UIImage.Orientation.up)
}
return cropped
}
让我告诉我我的错误以及我要做什么
我正在尝试拍照并根据任何视图的帧进行裁剪。我试图裁剪图片而不根据该主视图调整尺寸。因此,每次都以错误的方式进行裁剪。
我调整了图片大小,现在可以成功裁剪图片了。但是调整大小会降低图片的质量。所以现在我正努力寻找最好的方法。
谢谢
答案 0 :(得分:0)
您可以使用以下代码裁剪图像:
var invoice = new Invoice()
{
InvoiceNumber = "Inv099",
Amount = 66m,
InvoiceLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 1, Amount = 66m}
}
};
var creditNote = new CreditNote()
{
CreditNoteNumber = "DN002",
Amount = 99.99m,
CreditLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 3, Amount = 99.99m}
}
};
var debitNote = new DebitNote()
{
DebitNoteNumber = "CN008",
Amount = 77.77m,
DebitLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 2, Amount = 77.77m}
}
};
using (var context = new TestMVCEntities())
{
context.Invoices.Add(invoice);
context.CreditNotes.Add(creditNote);
context.DebitNotes.Add(debitNote);
context.SaveChanges();
}
传递您的图像和视图的矩形,您将从中心获取裁剪的图像
答案 1 :(得分:0)
您正在搜索 CIAffineTransform或CIPerspectiveCorrection。我不确定哪种方法更适合您的用例,但它们都应该都能工作。例如,您可以像这样使用CIPerspectiveCorrection:
(CIImageToWorkWith).applyingFilter("CIPerspectiveCorrection", parameters: [
"inputTopLeft" : CIVector(cgPoint: topleft),
"inputTopRight" : CIVector(cgPoint: topright),
"inputBottomLeft" : CIVector(cgPoint: bottomleft),
"inputBottomRight" : CIVector(cgPoint: bottomright)
])
编辑:您不想裁剪图像。裁剪就像在不缩放图像的情况下裁剪图像。
答案 2 :(得分:0)
我认为最简单的方法是:
extension UIImage {
func crop(to rect: CGRect) -> UIImage? {
guard let imageRef = cgImage, let cropped = imageRef.cropping(to: rect) else {
return nil
}
return UIImage(cgImage: cropped)
}
}