Method: UIImage#rotate

Defined in:
lib/sugarcube-image/uiimage.rb

#rotate(angle_or_direction) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/sugarcube-image/uiimage.rb', line 361

def rotate(angle_or_direction)
  case angle_or_direction
  when :left
    radian = -90.degrees
  when :right
    radian = 90.degrees
  when :flip
    radian = 180.degrees
  when Numeric
    radian = angle_or_direction
  else
    raise "Unknown angle/direction #{angle_or_direction.inspect}"
  end

  w = (self.size.width * Math.cos(radian)).abs + (self.size.height * Math.sin(radian)).abs
  h = (self.size.height * Math.cos(radian)).abs + (self.size.width * Math.sin(radian)).abs
  new_size = CGSize.new(w, h)
  new_size = self.size

  # Create the bitmap context
  UIGraphicsBeginImageContextWithOptions(new_size, false, self.scale)
  bitmap = UIGraphicsGetCurrentContext()

  # Move the origin to the middle of the image so we will rotate and scale around the center.
  CGContextTranslateCTM(bitmap, new_size.width / 2, new_size.height / 2)

  # Rotate the image context
  CGContextRotateCTM(bitmap, radian)

  # otherwise it'll be upside down:
  CGContextScaleCTM(bitmap, 1.0, -1.0)
  # Now, draw the rotated/scaled image into the context
  CGContextDrawImage(bitmap, CGRectMake(-new_size.width / 2, -new_size.height / 2, new_size.width, new_size.height), self.CGImage)

  new_image = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return new_image
end