IPhone : Rendering Text after Scaling and Rotating UITextView

on Wednesday, March 25, 2015

Problem


After scaling and rotating a UITextView using gestures, the text is sometimes fuzzy because the transformations are applied to the rasterized bitmap.


Proposed Solution


Once the gesture is complete, I need to return the transform to the identity transform, resize the frame based on the scale, resize the font based on the scale, and then re-apply the rotation transform.


Implementation Attempts



// Store original center before making changes

CGPoint originalCenter = textView.center;

// Restore transform to identity (frame property is invalid while transform is not identity)

[textView setTransform:CGAffineTransformIdentity];


// Attempt 1 - sizeThatFits /////////////////////////////////////////////////////////////////

// Scale font

[textView setFont:[UIFont fontWithName:textView.font.fontName size:textView.font.pointSize*scale]]; // scale refers to the scale of the pinch gesture that just ended

// Set frame to sizeThatFits

CGSize size = [textView sizeThatFits:maxSize]; // maxSize begins with the view frame size and is scaled at the end of each pinch gesture
[textView setFrame:CGRectMake(0, 0, size.width, size.height)];

// Restore Center

[textView setCenter:originalCenter];

// Re-apply rotation

[textView setTransform:CGAffineTransformMakeRotation(rotation)]; // refers to the total rotation from all rotation gestures


// Attempt 2 - manually scale /////////////////////////////////////////////////////////////////

// Scale font

[textView setFont:[UIFont fontWithName:textView.font.fontName size:textView.font.pointSize*scale]];

// Scale frame

[textView setFrame:CGRectMake(0, 0, textView.frame.size.width*scale, textView.frame.size.height*scale)];

// Restore Center

[textView setCenter:originalCenter];

// Re-apply rotation

[textView setTransform:CGAffineTransformMakeRotation(rotation)];


Notes


Everything I try almost works. In some cases, especially after multiple gestures (compounding the error), the text doesn't fit exactly right and will cause line breaks where there were none before.


0 comments:

Post a Comment