Combining text and images in `UITextView`
If I understand your goal, and how you currently have it implemented. You should check if you need to return first.
if ((cursorPosition.x + 30) >= message.frame.width) {
message.text = message.text.stringByAppendingString("\n");
}
Then you should get the now current cursor position, and add your UIImageView there.
let size = CGSize(width: 30, height: 30);
let img = UIImage(named: change_arr[indexPath.row]);
let addImg = UIImageView(image: UIImage(named: change_arr[indexPath.row]));
addImg.frame = CGRect(origin: newCursorPosition, size: size);
message.addSubview(addImg);
then if you need to add spaces, add them now.
As stated in the previous comments using NSTextAttachment will simplify all of this, and prevent you from having to create UIViews, etc...
it would look something like this, and you don't need to check for the cursor position, because it will handle that just like it does with text.
//create your UIImage
let image = UIImage(named: change_arr[indexPath.row]);
//create and NSTextAttachment and add your image to it.
let attachment = NSTextAttachment()
attachment.image = image
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
Now the image is inline, and treated like text. If the user backspaces over it, it deletes just like text.
UITextView with text and images combined
You can add the UIImageView
as a subView of UITextView
.
such like, Create an imageView with image:
UIImageView *imageView = [[UIImageView alloc] initWithImage:yourImage];
[imageView setFrame:yourFrame];
[yourTextView addSubview:imageView];
And This is source code might be helpful in your case:
https://github.com/HansPinckaers/GrowingTextView
https://github.com/enormego/EGOTextView
https://www.cocoacontrols.com/controls/imgglyph
https://www.cocoacontrols.com/controls/secoretextview
http://ios-blog.co.uk/featured-posts/ios-5-rich-text-editing-series/
How to add image and text in UITextView in IOS?
This is absolutely possible now, using
+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment
See Apple docs here
And this example taken from this other answer:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,140,140)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"before after"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"sample_image.jpg"];
CGFloat oldWidth = textAttachment.image.size.width;
//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView
CGFloat scaleFactor = oldWidth / (textView.frame.size.width - 10);
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(6, 1) withAttributedString:attrStringWithImage];
textView.attributedText = attributedString;
Using the above code will get you an image with text inside a UITextView on iOS 7+. You can/show style the attributed text as you want it and probably set the width of the image to make sure it fits within your textView (as well as setting your own aspect ratio/scale preference)
Here's a quick test image:
Add multiple images in UITextView long text
I solved the problem using a UIWebView
in place of the UITextView
. I render a local HTML page which is easier to customize in these cases.
Once you create your own HTML page in your favourite editor, you drag it into your Xcode project. Then you just have to tell your UIWebView
the path to the page to be rendered:
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "<name of html file>", ofType: "html", inDirectory: "<name of the directory>")!)
self.webView.loadRequest(URLRequest(url: url))
In my case, I put the html page and the images I render in a separate folder imported in the project; then you have to reference that folder when generating the URL.
For a better result I've set scalePageToFit = true
and disabled all the other options of the UIWebView
. Moreover, in order to disable the zooming by the user, I implemented the UIScrollViewDelegate
method viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
to simply returning nil
value to a better user experience.
Remember to set self.webView.scrollView.delegate = self
Combine label, textview and image (but image is scroll with text)
follow the step
view -> scrollview -> tableview
Inside tableview Header part used for UItextview and UIimageview for footer and if u place a label in imageview.
Set Image inline with text to UITextView in Objective C
You need to just use 'UIBezierPath'
For example,
txtvHtmlString.text = @“your long text…….”;
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(120, 100, 152, 128)];
imgView.image = [UIImage imageNamed:@"smily.png"];
imgView.layer.cornerRadius = 10;
[txtvHtmlString addSubview:imgView];
Then don't forget to update bezierpath in viewDidLayoutSubviews if your text is updated.
- (void)viewDidLayoutSubviews {
UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:imgView.frame];
txtvHtmlString.textContainer.exclusionPaths = @[exclusionPath];
}
How to combine TextView and an image and return an image?
You can try to draw text and lines on canvas.
Below is example method which draws text on drawable image and returns Bitmap
.
You can set custom font by calling .setTypeface()
on Paint
object.
Call canvas.drawLine()
to draw line. To customize your line you can create new Paint
object, set its color and width by .setColor()
and .setStrokeWidth()
and pass it in drawLine()
together with line coordinates.
public Bitmap drawTextOnBitmap(Context context, int resId, String text) {
// prepare canvas
Resources resources = context.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
// set default bitmap config if none
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are immutable, so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
// new antialiased Paint
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.rgb(61, 61, 61));
// text size in pixels
paint.setTextSize((int) (bitmap.getHeight() / 10 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
// set text width to canvas width minus 16dp padding
int textWidth = canvas.getWidth() - (int) (16 * scale);
// init StaticLayout for text
StaticLayout textLayout = new StaticLayout(text, paint, textWidth,
Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
// get height of multiline text
int textHeight = textLayout.getHeight();
// get position of text's top left corner
float x = (bitmap.getWidth() - textWidth) / 2;
float y = (bitmap.getHeight() - textHeight) / 2;
// draw text to the Canvas center
canvas.save();
canvas.translate(x, y);
textLayout.draw(canvas);
canvas.restore();
return bitmap;
}
Update:
To draw rectangle add this to the method:
Paint p = new Paint();
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(24);
RectF rectF = new RectF(80, 150, 200, 350);
canvas.drawRect(rectF, p);
Parameters for new RectF():
left
The X coordinate of the left side of the rectangle
top
The Y coordinate of the top of the rectangle
right
The X coordinate of the right side of the rectangle
bottom
The Y coordinate of the bottom of the rectangle
iOS 7 TextKit - How to insert images inline with text?
You'll need to use an attributed string and add the image as instance of NSTextAttachment
:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"like after"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"whatever.png"];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage];
Combine label, textview and image (but image is scroll with text)
follow the step
view -> scrollview -> tableview
Inside tableview Header part used for UItextview and UIimageview for footer and if u place a label in imageview.
Related Topics
Xcode 6.4/7 Crashing After El Capitan Beta
(iOS + Storekit) How to Detect When I'm in the Sandbox
How to Check If Haptic Engine (Uifeedbackgenerator) Is Supported
Intercept Request with Wkwebview
Alphabetical Sections in Table Table View in Swift
Not Receiving Any Push Notification in Iphone
Storyboard Navigation Controller and Tab Bar Controller
How to Use the Default iOS7 Uianimation Curve
Push/Pop View Controller with Navigation Bar from View Controller Without Navigation Bar
Swift Calculate Md5 Checksum for Large Files
Best Way to Save and Retrieve Uicolors to Core Data
How to Write Application Logs to File and Get Them
How to Change the App Store's Large Icon on Itunes Connect
Uirefreshcontrol Stuck After Switching Tabs in Uitabbarcontroller
iOS Enterprise Provisioning Profile Expiration