Gradient text fill using GD - PHP - text

I need a function that renders gradient on a text using GD
something like
function gradientText($text,$font,$color1,$color2)
{
..
}

I suggest you try to build that function based your own needs.
You will want to center the text vertically/horizontal, change font size, etc...
Start on this function by Christopher Kramer, code is also below this answer...
http://www.php.net/manual/en/function.imagefill.php#93920
then you can use imagettfbbox if you want to use custom font files.
http://www.php.net/manual/en/function.imagettfbbox.php
Here is a sample image I generated using those 2 functions.
Pasting Chris' code of gradient here for reference:
<?php
function gradient($w=100, $h=100, $c=array('#FFFFFF','#FF0000','#00FF00','#0000FF'), $hex=true) {
/*
Generates a gradient image
Author: Christopher Kramer
Parameters:
w: width in px
h: height in px
c: color-array with 4 elements:
$c[0]: top left color
$c[1]: top right color
$c[2]: bottom left color
$c[3]: bottom right color
if $hex is true (default), colors are hex-strings like '#FFFFFF' (NOT '#FFF')
if $hex is false, a color is an array of 3 elements which are the rgb-values, e.g.:
$c[0]=array(0,255,255);
*/
$im=imagecreatetruecolor($w,$h);
if($hex) { // convert hex-values to rgb
for($i=0;$i<=3;$i++) {
$c[$i]=hex2rgb($c[$i]);
}
}
$rgb=$c[0]; // start with top left color
for($x=0;$x<=$w;$x++) { // loop columns
for($y=0;$y<=$h;$y++) { // loop rows
// set pixel color
$col=imagecolorallocate($im,$rgb[0],$rgb[1],$rgb[2]);
imagesetpixel($im,$x-1,$y-1,$col);
// calculate new color
for($i=0;$i<=2;$i++) {
$rgb[$i]=
$c[0][$i]*(($w-$x)*($h-$y)/($w*$h)) +
$c[1][$i]*($x *($h-$y)/($w*$h)) +
$c[2][$i]*(($w-$x)*$y /($w*$h)) +
$c[3][$i]*($x *$y /($w*$h));
}
}
}
return $im;
}
function hex2rgb($hex)
{
$rgb[0]=hexdec(substr($hex,1,2));
$rgb[1]=hexdec(substr($hex,3,2));
$rgb[2]=hexdec(substr($hex,5,2));
return($rgb);
}
// usage example
$image=gradient(300, 300, array('#000000', '#FFFFFF', '#FF0000', '#0000FF'));
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

Using GD
http://planetozh.com/blog/my-projects/images-php-gd-gradient-fill/ offers a class to create a gradient with GD.
Gradient can be linear (horizontal or vertical), radial, rectangle, diamond. That's the same options you would find on Adobe Photoshop.
The class methods fill rectangular areas with a gradient, so you could achieve a rather great gradient effect with the following method:
create a gradient rectangle with this class
write your text in the specified font
mix them:
you could cut the gradient picture with the shape of the text picture
you could apply the gradient picture as a pattern for the text picture
Using ImageMagick
Instead to use GD, I would use ImageMagick.
See http://www.imagemagick.org/Usage/fonts/#gradient for a sample of how to use ImageMagick to achieve that, and http://www.imagemagick.org/Usage/canvas/#gradient for all the gradients options.

Related

SwiftUI tint for image but preserving Black and White

I need to shift the color in an image, e.g. from gray to green. But only the parts that are not white and/or black...
For UIKit I had a handy extension:
// colorize image with given tint color
// this is similar to Photoshop's "Color" layer blend mode
// this is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved
// white will stay white and black will stay black as the lightness of the image is preserved
func tint(tintColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
context.setBlendMode(.normal)
UIColor.black.setFill()
context.fill(rect)
// draw original image
context.setBlendMode(.normal)
context.draw(self.cgImage!, in: rect)
// tint image (loosing alpha) - the luminosity of the original image is preserved
context.setBlendMode(.color)
tintColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(self.cgImage!, in: rect)
}
}
is there any way to generate the same functionality with the tint options in SwiftUI?
".colorMultiply" colors white as well.
".saturation(0.5)" directly generates a grayscale image.
You can continue to use your extension, like
var body: some View {
Image(uiImage: UIImage(named: "some")!.tint(tintColor: UIColor.red))
}
I was looking for the wrong keyword.
The actually way to do this in SwiftUI is hueRotation!
It only works with coloured images and not with grayscale images though.
See example below:
Color.blue
.hueRotation(.degrees(-45.0))

How to find bit length of text with specific font and font size

I'm developing NativeScript JavaScript code to create dynamic text marker for maps. I have the code working that creates a marker for a specific string. My next step is to take any given string, determine its height and width in bits, and create the marker sized to contain the text.
My problem is finding the size of the text, given the text string itself, the font size, and the font family.
It looks like getMeasuredWidth could work, except that the string must already be loaded on a page before that function will return a value. In my case, I simply need to compute the size; the text won't otherwise appear as such on a page (the text in the marker becomes an image).
Is there a way to do this?
var bmp = BitmapFactory.create(200);
bmp.dispose(function (b) {
try {
b.drawRect(
"100,34", // size
'0,0', // upper-left coordinate
KnownColors.Black, // border color
KnownColors.Cornsilk // fill color
);
b.writeText(
"Parking",
"2,25",
{ color: KnownColors.Black, size: 8, name: 'fontawesome-webfont', });
...
In the code above, the width of "100" of the bounding rectangle actually represents the bit width of "Parking" with a small amount of padding. What I want to does calculate the rectangle's height and width and not hard-code it.
Try this, finding label size without adding it to Page upon button click
export function onFindButtonTap(args: EventData) {
const button = <any>args.object;
const label = new Label();
label.text = "Hello, found my size?"
label.fontSize = 20;
(<any>label)._setupAsRootView(button._context);
label.onLoaded();
label.measure(0, 0);
console.log(`Width : ${label.getMeasuredWidth()} x Height : ${label.getMeasuredHeight()}`);
}
Playground Sample
Note: I didn't get a chance to test it with iOS yet, let me know if you hit any issues.

Extendscript: How to check whether text content overflows the containing rectangle

I am using Extendscript for Photoshop CS5 to change the text of a text layer. Is there a way of checking whether the text fits e.g. by checking whether it overflows after changing the content?
I created a solution that works perfectly fine :). Maybe someone else can use it as well. Let me know if it works for you too!
function scaleTextToFitBox(textLayer) {
var fitInsideBoxDimensions = getLayerDimensions(textLayer);
while(fitInsideBoxDimensions.height < getRealTextLayerDimensions(textLayer).height) {
var fontSize = parseInt(textLayer.textItem.size);
textLayer.textItem.size = new UnitValue(fontSize * 0.95, "px");
}
}
function getRealTextLayerDimensions(textLayer) {
var textLayerCopy = textLayer.duplicate(activeDocument, ElementPlacement.INSIDE);
textLayerCopy.textItem.height = activeDocument.height;
textLayerCopy.rasterize(RasterizeType.TEXTCONTENTS);
var dimensions = getLayerDimensions(textLayerCopy);
textLayerCopy.remove();
return dimensions;
}
function getLayerDimensions(layer) {
return {
width: layer.bounds[2] - layer.bounds[0],
height: layer.bounds[3] - layer.bounds[1]
};
}
How to use / Explanation
Create a text layer that has a defined width and height.
You can change the text layers contents and then call scaleTextToFitBox(textLayer);
The function will change the text/font size until the text fits inside the box (so that no text is invisible)!
The script decreases the font size by 5% (* 0.95) each step until the texts fits inside the box. You can change the multiplier to achieve a more precise result or to increase performance.
I haven't found a way to do this directly. But I've used the following technique to determine the height I needed for a textbox (I wanted to keep the width constant) before.
expand the textbox's height well beyond what is needed to accommodate the text inside it.
duplicate the layer
rasterize the duplicate
measure the bounds of the rasterized layer.
adjust the bounds of the original text layer as needed
delete the rasterized duplicate
Totally roundabout - but it did work.

AndroidPlot - Labels and text

I am a non-developer product manager for an application built in both Android and iOS. We have a bar graph in iOS that provides text for the content of the graph. It displays Totals for each bar, and percentages for each segment of each bar.
In Android, using AndroidPlot (so I understand) we just display the bars with different color segments and no percent totals or totals. I am told by the developer that we can't show more.
I would display the images here, but stackoverflow tells me I don't have enough reputation points to do this. I have created a link to my dropbox with the images https://www.dropbox.com/sh/2uocm5bn79rerbe/AAB7s9QEEYIRIgXhKbUAaOyDa
Is it possible to use AndroidPlot to emulate this iOS chart or at least represent to same information to the end user?
Your developer is more or less correct but you have options. Androidplot's BarRenderer by default provides only an optional label at the top of each bar, which in your iOS images is occupied by the "available", "new", "used" and "rent" label. That label appears to be unused in your Android screenshot so one option would be to utilize those labels do display your totals.
As far as exactly matching the iOS implementation with Androidplot, the missing piece is the ability to add additional labels horizontally and vertically along the side of each bar. You can extend BarRenderer to do this by overriding it's onRender(...) method. Here's a link for your developer that shows where in the code he'll want to modify onRender(...).
I'd suggest these modifications to add the vertical labels:
Invoke Canvas.save(Canvas.ALL_SAVE_FLAG) to store the default orientation of the Canvas.
Use Canvas.translate(leftX, bottom) to center on the bottom left point of the bar
Rotate the Canvas 90 degrees using Canvas.rotate(90) to enable vertical text drawing
Draw whatever text is needed along the side of the plot; 0,0 now corresponds to the bottom left corner of the bar so start there when invoking canvas.drawText(x,y).
Invoke Canvas.restore() to restore the canvas' original orientation.
After implementing the above, adding horizontal "%" labels should be self evident but if you run into trouble feel free to ask more questions along the way.
UPDATE:
Here's a very basic implementation of the above. First the drawVerticalText method:
/**
*
* #param canvas
* #param paint paint used to draw the text
* #param text the text to be drawn
* #param x x-coord of where the text should be drawn
* #param y y-coord of where the text should be drawn
*/
protected void drawVerticalText(Canvas canvas, Paint paint, String text, float x, float y) {
// record the state of the canvas before the draw:
canvas.save(Canvas.ALL_SAVE_FLAG);
// center the canvas on our drawing coords:
canvas.translate(x, y);
// rotate into the desired "vertical" orientation:
canvas.rotate(-90);
// draw the text; note that we are drawing at 0, 0 and *not* x, y.
canvas.drawText(text, 0, 0, paint);
// restore the canvas state:
canvas.restore();
}
All that's left is to invoke this method where necessary. In your case it should be done once per BarGroup and should maintain a consistent position on the y axis. I added the following code to the STACKED case in BarRenderer.onRender(...), immediately above the break:
// needed some paint to draw with so I'll just create it here for now:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(PixelUtils.spToPix(20));
drawVerticalText(
canvas,
paint,
"test",
barGroup.leftX,
basePositionY - PixelUtils.dpToPix(50)); // offset so the text doesnt intersect with the origin
Here's a screenshot of the result...sorry it's so huge:
Personally, I don't care for the fixed y-position of these vertical labels and would prefer them to float along the upper part of the bars. To accomplish this I modify my invocation of drawVerticalText(...) to look like this:
// needed some paint to draw with so I'll just create it here for now:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(PixelUtils.spToPix(20));
// right-justify the text so it doesnt extend beyond the top of the bar
paint.setTextAlign(Paint.Align.RIGHT);
drawVerticalText(
canvas,
paint,
"test",
barGroup.leftX,
bottom);
Which produces this result:

How to change bitmap image runtime based on condition and set on canvas?

I have nine rectangles drawn on canvas and I had set image on it through bitmap by decoding it from resources. I am generating random numbers between 1 to 10 and set it to text view.
When user moves to rectangle based on number displaying in text view the image of that particular rectangle should be changed
if(textview.getText().toString()==1)
{
canvas.drawBitmap(bitmapHolo,null,rect[i],null);
}
else
{
canvas.drawBitmap(bitmapRectangle,null,rect[i],null);
}

Resources