简体   繁体   中英

skewing a UIImageView using CGAffineTransform

I am trying to skew a rectangle so the two vertical sides are slanted but parallel and the top and bottom are horizontal.

I am trying to use CGAffineTransform and have found this code but I am not figuring out what to put in the various parts.

imageView.layer.somethingMagic.imageRightTop = (CGPoint){ 230, 30 };
                imageView.layer.somethingMagic.imageRightBottom = (CGPoint){ 300, 150 };

#define CGAffineTransformDistort(t, x, y) (CGAffineTransformConcat(t, CGAffineTransformMake(1, y, x, 1, 0, 0)))
#define CGAffineTransformMakeDistort(x, y) (CGAffineTransformDistort(CGAffineTransformIdentity, x, y))

although this is said to be easy I don't know what to put in the different places.

I assume image view would be my image that I want to change however what goes into somethingMagic. and imageRightTop and imageRightBottom.

Also how do I define t.

If there is a more thorough explanation I would appreciate it since in most cases I found only this as the explanation of what to do to skew a rectangle.

Thanks

Let's assume you have a variable named imageView holding a reference to your UIImageView .
I wrote a little sample to demonstrate how you could get this behavior. What this code does is creating a new CGAffineTransform matrix. This matrix has the same values as the identity transform matrix with one exception: the value at location [2,1]. This value is controlled by the c -parameter of the CGAffineTransformMake -function and controls the shearing along the x-axis. You can change the amount of shearing by setting shearValue .

The code:

Objective-C

CGFloat shearValue = 0.3f; // You can change this to anything you want
CGAffineTransform shearTransform = CGAffineTransformMake(1.f, 0.f, shearValue, 1.f, 0.f, 0.f);
[imageView setTransform:shearTransform];

Swift 5

let shearValue = CGFloat(0.3) // You can change this to anything you want
let shearTransform = CGAffineTransform(a: 1, b: 0, c: shearValue, d: 1, tx: 0, ty: 0)
imageView.transform = shearTransform

And here's what the shearTransform -matrix looks like:

[1     0     0]  
[0.3   1     0]  
[0     0     1]   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM