如何快速裁剪图​​像

时间:2015-09-12 06:57:07

标签: swift uiimageview uiimage

在我的项目中,我有一个方形格式的UIImageView用于用户配置文件的图像,但是当我从库中添加图像时,它看起来没有形状。我找到了一个代码来将图像裁剪成方形格式,但我不知道在我的代码中将其插入到从库或新照片中裁剪所选图像的位置。你能帮助我吗? 代码如下:

ImageUtil.swift

import UIKit

class ImageUtil: NSObject {

 func cropToSquare(image originalImage: UIImage) -> UIImage {
    // Create a copy of the image without the imageOrientation property so it is in its native orientation (landscape)
    let contextImage: UIImage = UIImage(CGImage: originalImage.CGImage)!

    // Get the size of the contextImage
    let contextSize: CGSize = contextImage.size

    let posX: CGFloat
    let posY: CGFloat
    let width: CGFloat
    let height: CGFloat

    // Check to see which length is the longest and create the offset based on that length, then set the width and height of our rect
    if contextSize.width > contextSize.height {
        posX = ((contextSize.width - contextSize.height) / 2)
        posY = 0
        width = contextSize.height
        height = contextSize.height
    } else {
        posX = 0
        posY = ((contextSize.height - contextSize.width) / 2)
        width = contextSize.width
        height = contextSize.width
    }

    let rect: CGRect = CGRectMake(posX, posY, width, height)

    // Create bitmap image from context using the rect
    let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)

    // Create a new image based on the imageRef and rotate back to the original orientation
    let image: UIImage = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)!

    return image
}

}

AddController.swift

import UIKit

class AddController: UIViewController, UITextFieldDelegate, CameraManagerDelegate {


@IBOutlet var immagine: UIImageView!
@IBOutlet var fieldNome: UITextField!


var immagineSelezionata : UIImage?


override func viewDidLoad() {
    super.viewDidLoad()

    navigationController!.navigationBar.barStyle = UIBarStyle.BlackTranslucent

    navigationController!.navigationBar.tintColor = UIColor.whiteColor()

    navigationController!.navigationBar.barTintColor = UIColor(red: 60/255.0, green: 172/255.0, blue: 183/255.0, alpha: 1.0)

    //navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))

    //tableView.backgroundColor = UIColor(red: 60/255.0, green: 172/255.0, blue: 183/255.0, alpha: 1.0)

    UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)

    let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "selezionaFoto:")
    singleTap.numberOfTapsRequired = 1
    singleTap.numberOfTouchesRequired = 1
    self.immagine.addGestureRecognizer(singleTap)
    self.immagine.userInteractionEnabled = true

    fieldNome.delegate = self
    CameraManager.sharedInstance.delegate = self


    var keyboardToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 44))
    keyboardToolbar.barStyle = UIBarStyle.BlackTranslucent
    keyboardToolbar.backgroundColor = UIColor(red: 60/255.0, green: 172/255.0, blue: 183/255.0, alpha: 1.0)
    keyboardToolbar.tintColor = UIColor.whiteColor()
    var flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var save = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""),
        style: UIBarButtonItemStyle.Done,
        target: fieldNome,
        action: "resignFirstResponder")
    keyboardToolbar.setItems([flex, save], animated: false)
    fieldNome.inputAccessoryView = keyboardToolbar
}

func myUIImageViewTapped(recognizer: UITapGestureRecognizer) {
    if(recognizer.state == UIGestureRecognizerState.Ended){
        println("myUIImageView has been tapped by the user.")
    }
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



@IBAction func annulla(sender: UIBarButtonItem) {
    dismissViewControllerAnimated(true, completion: nil) 
}




@IBAction func salva(sender: UIBarButtonItem) {
    if fieldNome.text.isEmpty
        {

            return
    }

    var profilo = ProfiloModel(nomeIn: fieldNome.text,
        immagineIn: UIImage(named:"icon-profile")!)

    if let img = immagineSelezionata {
        profilo.immagine = img
    }



    //DataManager.sharedInstance.storage.insert(profilo, atIndex: 0)
    DataManager.sharedInstance.storage.append(profilo)
    DataManager.sharedInstance.salvaArray()
    DataManager.sharedInstance.master.tableView.reloadData()

    dismissViewControllerAnimated(true, completion: nil)
}




@IBAction func selezionaFoto(sender: UITapGestureRecognizer) {

    fieldNome.resignFirstResponder()

    func selezionaLibreria(action : UIAlertAction!) {
        UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
        CameraManager.sharedInstance.newImageFromLibraryForController(self, editing: false)
    }

    func scattaFoto(action : UIAlertAction!) {
        UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
        var circle = UIImageView(frame: UIScreen.mainScreen().bounds)
        circle.image = UIImage(named: "overlay")
        CameraManager.sharedInstance.newImageShootForController(self, editing: false, overlay:circle)
    }

    var myActionSheet = UIAlertController(title: NSLocalizedString("ACTION_IMAGE_TITLE", comment: ""),
        message: NSLocalizedString("ACTION_IMAGE_TEXT", comment: ""),
        preferredStyle: UIAlertControllerStyle.ActionSheet)

    myActionSheet.addAction(UIAlertAction(title: NSLocalizedString("BUTTON_LIBRARY", comment: ""),
        style: UIAlertActionStyle.Default,
        handler: selezionaLibreria))

    myActionSheet.addAction(UIAlertAction(title: NSLocalizedString("BUTTON_SHOOT", comment: ""),
        style: UIAlertActionStyle.Default,
        handler: scattaFoto))

    myActionSheet.addAction(UIAlertAction(title: NSLocalizedString("BUTTON_CANCEL", comment: ""),
        style: UIAlertActionStyle.Cancel,
        handler: nil))

    self.presentViewController(myActionSheet, animated: true, completion: nil)

}


func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder() // chiudere la tastiera nei campi di testo
    return true
}

func incomingImage(image: UIImage) {
    UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
    immagine.image = image
    immagineSelezionata = image
}

func cancelImageSelection() {
    UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
}



}

2 个答案:

答案 0 :(得分:0)

我找到了一个链接可以帮到你

  

CGBitmapContextCreate& CGContextDrawImage

     

Core Graphics / Quartz 2D提供了一套较低级别的API,可以进行更高级的配置。给定CGImage,使用CGBitmapContextCreate()和

,使用临时位图上下文渲染缩放图像
CGBitmapContextCreateImage():

let image = UIImage(contentsOfFile: self.URL.absoluteString!).CGImage

let width = CGImageGetWidth(image) / 2.0
let height = CGImageGetHeight(image) / 2.0
let bitsPerComponent = CGImageGetBitsPerComponent(image)
let bytesPerRow = CGImageGetBytesPerRow(image)
let colorSpace = CGImageGetColorSpace(image)
let bitmapInfo = CGImageGetBitmapInfo(image)

let context = CGBitmapContextCreate(nil, width, height, 

bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)

CGContextSetInterpolationQuality(context, kCGInterpolationHigh)

CGContextDrawImage(context, CGRect(origin: CGPointZero, size:  CGSize(width: CGFloat(width), height: CGFloat(height))), image)

let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context))
  

CGBitmapContextCreate采用多个参数来构造具有所需尺寸和给定颜色空间内每个通道的内存量的上下文。在该示例中,这些值是从CGImage中获取的。接下来,CGContextSetInterpolationQuality允许上下文以各种保真度级别插入像素。在这种情况下,传递kCGInterpolationHigh以获得最佳结果。 CGContextDrawImage允许以给定的大小和位置绘制图像,允许在特定边缘上裁剪图像或适合一组图像特征,例如面部。最后,CGBitmapContextCreateImage从上下文创建CGImage。

字体Image Resizing Techiniques

答案 1 :(得分:-1)

请参阅Image-Cropper

摘录:

JNIEXPORT void JNICALL Java_xxoo_com_xxoo_model_ARDrawModel_draw(JNIEnv * env, jobject obj) {
    try {
        if(controller)
        {
            controller->Update(/*float dt*/);
            controller->DrawGLScene();
        }
    } catch (int a) {
        LOGD("drawModel---exception");

    }
}

该代码允许您放大和缩小所选图片,移动它并裁剪该图片的所需区域。它实现起来很简单,一切都在ViewController上完成。希望这能解决你的问题。

相关问题