i want to set custom font for TextView in widget,How?
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget);
views.setTextViewText(R.id.txv_widget_location, "my text");
Just replace xyz.ttf with your chosen font.
public Bitmap createBitmap(String texttoshow)
{
Bitmap myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_8888);
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface weatherwidget = Typeface.createFromAsset(this.getAssets(),"xyz.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(weatherwidget);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(65);
paint.setTextAlign(Align.CENTER);
myCanvas.drawText(texttoshow, 80, 60, paint);
return myBitmap;
}
The above code applies the font and text to image view.
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.weather_widget);
views.setImageViewBitmap(R.id.txv_widget_location, createBitmap("my_text"));
Related
I have a gear image which I want to continuously rotate about a fixed point.
Earlier I was accomplishing this by including the image in my Android class as an ImageView and applying a RotateAnimation to it.
#InjectView(R.id.gear00) ImageView gear00;
RotateAnimation ra07 = new RotateAnimation(0, 359, 129, 186);
ra07.setDuration(10000);
ra07.setRepeatCount(RotateAnimation.INFINITE);
ra07.setInterpolator(new LinearInterpolator());
gear00.setAnimation(ra07);
Basically, I was injecting the ImageView into the class and applying a rotation animation.
However, I dont have the luxury of using an ImageView anymore. I have to use a Bitmap and rotate it on the canvas.
How can I go about accomplishing what I was doing earlier in the onDraw() method with a bitmap rotating about a fixed point continiously on the canvas?
Edit1:
I tried one of the suggestions mentioned below my code looks a little like the following
in onCreate():
Matrix matrix = new Matrix();
matrix.setRotate(10, 100, 200);
Then in onDraw() (where gear00Scaled is a bitmap to be rotated on the canvas):
canvas.drawBitmap(gear00Scaled, matrix, new Paint());
Another method I tried involved saving the canvas, rotating it, then restoring it:
canvas.save();
canvas.rotate(10);
canvas.drawBitmap(gear00Scaled, 100, 200, null);
canvas.restore();
Neither seem to be working though!
Make an XML class (suppose: rotate.xml) and place it in res/anim folder and then write the following code in it:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:interpolator="#android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" />
Then in your java class, do the following in OnCreate:
final Animation a = AnimationUtils.loadAnimation(CustomActivity.this,
R.anim.rotate);
a.setDuration(3000);
gear00.startAnimation(a);
OR
To do it using bitmap, I hope the following sequence of code helps you:
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());
If you check the following method from:
~frameworks\base\graphics\java\android\graphics\Bitmap.java
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
Matrix m, boolean filter)
this would explain what it does with rotation and translate.
I want to rotate a custom image as progress dialog in my application. You can use the code below to rotate an image:
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f ,
Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(1000);
imageView.setAnimation(anim);
imageView.startAnimation(anim);
In your onCreate() do
Matrix matrix = new Matrix();
And in onDraw
float angle = (float) (System.currentTimeMillis() % ROTATE_TIME_MILLIS)
/ ROTATE_TIME_MILLIS * 360;
matrix.reset();
matrix.postTranslate(-source.getWidth() / 2, -source.getHeight() / 2);
matrix.postRotate(angle);
matrix.postTranslate(centerX, centerY)
canvas.drawBitmap(source, matrix, null);
invalidate(); // Cause a re-draw
ROTATE_TIME_MILLIS is the full circle time, e.g. 2000 is 2 seconds.
Two things before the code:
You can't use imageview at all at all? Cause you could link it to a canvas and use a bitmap, but it is still an imageview.
I believe the main issue you are having is the other answer is not animating it and you are missing the call to invalidate() the view and redraw it as rotated.
So there are two approaches:
1st is with the imageview, personally I think it is easier and nicer. Below is a method in my activity class and mLittleChef is an ImageView.
public void doCanvas(){
//Create our resources
Bitmap bitmap = Bitmap.createBitmap(mLittleChef.getWidth(), mLittleChef.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final Bitmap chefBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.dish_special);
//Link the canvas to our ImageView
mLittleChef.setImageBitmap(bitmap);
ValueAnimator animation= ValueAnimator.ofFloat(0, 359, 129, 186);
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (Float) animation.getAnimatedValue();
//Clear the canvas
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.save();
canvas.rotate(value, canvas.getWidth()/2, canvas.getHeight()/2);
canvas.drawBitmap(chefBitmap, 0, 0, null);
canvas.restore();
mLittleChef.invalidate();
}
});
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(1000);
animation.start();
}
The other way to do it is with a custom canvas class. Instead of an ImageView, I create my own custom view class for ExampleDrawView mLittleChefDraw; in my layout. You will probably have to monkey with this one a bit to get exactly what you are looking for in terms of rotation, I made it just do a 360 degree turn using the middle of the canvas as the pivot point.
public class ExampleDrawView extends View {
Bitmap bitmap;
Float mRotate= 0f;
Handler h;
//State variables
final int STATE_PAUSE = 2;
final int STATE_ROTATE = 3;
int STATE_CURRENT;
public ExampleDrawView(Context context, AttributeSet attrs) {
super(context, attrs);
h = new Handler();
bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.dish_special);
STATE_CURRENT= STATE_PAUSE;
}
Runnable move = new Runnable() {
#Override
public void run() {
switch (STATE_CURRENT){
case STATE_ROTATE:
if (mRotate<360){
mRotate++;
invalidate();
}else{
STATE_CURRENT= STATE_PAUSE;
}
h.postDelayed(move, 20);
break;
}
}
};
public void startDrawing(){
if(STATE_CURRENT == STATE_PAUSE){
STATE_CURRENT= STATE_ROTATE;
mRotate=(float) 0;
h.postDelayed(move, 20);
}
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
//change your rotate point here, i just made it the middle of the canvas
canvas.rotate(mRotate,getWidth()/2,getHeight()/2);
canvas.drawBitmap(bitmap, 0, 0, null);
}
}
And then back in the activity call this to start it:
public void doCanvasCustomView(){
mLittleChefDraw.startDrawing();
}
I am using the android Paint class to create text. I know how to set text size and color. I want to use Arial as font size and bold. How can I do it using the paint object. I have looked on the methods in the Paint class but couldn't find anything on how I can do it.
This is how I create my text style.
// Defining a paint object
paint = new Paint();
paint.setTextSize(30);
paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
Here is how I draw the text on a view.
g.drawString("My Text", 430, 774, paint);
How do I create the Arial font and bold text using the Paint class.
Use the TextPaint class instead of Paint. And can be implemented as below
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(30);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setColor(Color.WHITE);
textPaint.setTypeface(Typeface.create("Arial", Typeface.BOLD));
Januari 2020
Copy the fonts you want to use to res/font
(e.g. opensans_regular.ttf, opensans_italic.ttf, opensans_bolditalic.ttf, etc.)
Watch out no '-' of capitals in the name!
Create New Font resource file opensans.xml
<?xml version="1.0" encoding="utf-8"?>
<font-family
xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:fontStyle="normal"
app:fontWeight="400"
app:font="#font/opensans_regular" />
<font
app:fontStyle="italic"
app:fontWeight="400"
app:font="#font/opensans_italic" />
<font
app:fontStyle="normal"
app:fontWeight="700"
app:font="#font/opensans_bold" />
<font
app:fontStyle="italic"
app:fontWeight="700"
app:font="#font/opensans_bolditalic" />
<font
app:fontStyle="normal"
app:fontWeight="200"
app:font="#font/opensans_light" />
<font
app:fontStyle="italic"
app:fontWeight="200"
app:font="#font/opensans_lightitalic" />
<font
app:fontStyle="normal"
app:fontWeight="800"
app:font="#font/opensans_extrabold" />
<font
app:fontStyle="italic"
app:fontWeight="800"
app:font="#font/opensans_extrabolditalic" />
</font-family>
In your MainActivity.java you can use the following code
Paint paint = new Paint();
Typeface typeface;
if (Build.VERSION.SDK_INT >= 28) {
// This does only works from SDK 28 and higher
Typeface typefaceA = ResourcesCompat.getFont(this, R.font.opensans);
typeface = Typeface.create(typefaceA, 700, false);
} else {
// This always works (Whole name without .ttf)
typeface = ResourcesCompat.getFont(this, R.font.opensans_bolditalic);
}
paint.setTypeface(typeface);
private Bitmap getFontBitmap(String text, int color, float fontSizeSP, int typefaceStyle, boolean isCustomFont) {
Paint paint = new Paint();
paint.setAntiAlias(true);
if (isCustomFont) {
Typeface typeface = Typeface.create(Typeface.createFromAsset(mContext.getAssets(), "fonts/bangla/bensen_handwriting.ttf"), typefaceStyle);
paint.setTypeface(typeface);
} else {
Typeface typeface = Typeface.create(Typeface.DEFAULT, typefaceStyle);
paint.setTypeface(typeface);
}
int fontSizePX = ConvertDptoPx(mContext, fontSizeSP);
int pad = (fontSizePX / 9);
paint.setColor(color);
paint.setTextSize(fontSizePX);
int textWidth = (int) (paint.measureText(text) + pad * 2);
int height = (int) (fontSizePX / 0.75);
Bitmap bitmap = Bitmap.createBitmap(textWidth, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
float xOriginal = pad;
canvas.drawText(text, xOriginal, fontSizePX, paint);
return bitmap;
}
private int ConvertDptoPx(Context context, float dip) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
}
And then call
Bitmap bitmap = getFontBitmap("Ahamadullah", color, 22, Typeface.BOLD, true);
or
Bitmap bitmap = getFontBitmap("Ahamadullah", color, 22, Typeface.NORMAL | Typeface.ITALIC, false);
I am trying to resize a picture and save it however the picture I am saving is not resized.
Here is the code I am trying use.
if(CC_Files.fileExists(path)){
if(path.contains(".jpg") || path.contains(".png") || path.contains(".gif") ){
Image image = (Image) SWTResourceManager
.getImage(path);
ImageData imgData = image.getImageData();
imgData.scaledTo(150, 150);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] {imgData};
imageLoader.save(Variables.getStrResources() + "\\Pics\\" + a.getHerd_id() + ".jpg",SWT.IMAGE_JPEG);
}
}
Your problem is that you do not read the JavaDoc where is wrriten
ImageData#scaledTo(int width, int height) - Returns a copy of the receiver which has been stretched or shrunk to the specified size.
So the solution is:
imgData = imgData.scaledTo(150, 150);
Documentation
Java SWT Image Resize is proper Working
ImageLoader class are used to load images from, and save images to, a file or stream
imageLoader.save(result, SWT.IMAGE_COPY)
FileDialog class allow the user to navigate the file system and select or enter a file name.
Button btnOpen = new Button(parent, SWT.NONE);
btnOpen.setBounds(200, 55, 68, 23);
btnOpen.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
String result = dialog.open();
if(result!=null)
{
Image image=SWTResourceManager.getImage(result);
//ImageData class are device-independent descriptions of images
ImageData imgData = image.getImageData();
imgData=imgData.scaledTo(200, 200);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] {imgData};
imageLoader.save(result, SWT.IMAGE_COPY);
System.out.println("Width: "+imgData.width+".....Height: "+imgData.height);
lbl_image_text.setBounds(25,88,imgData.width+10,imgData.height+10);
lbl_image_text.setImage(SWTResourceManager.getImage(result));
}
}
});
btnOpen.setText("open");
CLabel lbl_image_text = new CLabel(parent, SWT.Resize);
Image size set to Label Dynamically
Button btnOpen = new Button(parent, SWT.NONE);
btnOpen.setBounds(200, 55, 68, 23);
btnOpen.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
String result = dialog.open();
if(result!=null)
{
Image image=SWTResourceManager.getImage(result);
//get Image width and height
lbl_image_text.setBounds(25,88,image.getBounds().width+10,image.getBounds().height+10);
lbl_image_text.setImage(SWTResourceManager.getImage(result));
}
}
});
btnOpen.setText("open");
CLabel lbl_image_text = new CLabel(parent, SWT.Resize);
Call this method from the SWT.addListener(SWT.Close, new CustomShellCloseListener()). Tha parameters required to pass are LabelImage(Do not Use Label.getImage() ,pass the direct path),label.getBounds.width ,label.getBounds.height
protected Image resize(Image imageFromSource, int width, int height) {
if(width>0 && height>0){
Image scaledImage = new Image(shellCCMPFMatrixBomCompare.getDisplay(), width, height);
GC gc = new GC(scaledImage); //Graphics Capabilities(GC instance) in SWT used to draw an Image, graphics, display
gc.setAntialias(SWT.ON); // Anti aliasing is used for making the low resolution image to redraw and make into a good resolution Image
gc.setInterpolation(SWT.HIGH); //Interpolation is based in the Graphics, it may not work properly in some systems
gc.drawImage(imageFromSource, 0, 0,
imageFromSource.getBounds().width, imageFromSource.getBounds().height,
0, 0, width, height);
/*drawImage(Image image, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight)
Copies a rectangular area from the source image into a (potentially different sized) rectangular area in the receiver.*/
gc.dispose();
return scaledImage;
}
else return imageFromSource;
}
I had created an image by the following code:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
try {
int tile1ResID = getResources().getIdentifier("drawable/m" + String.valueOf(tileOfPoint.x) + "_" + String.valueOf(tileOfPoint.y), "drawable", "com.example.sabtt1");
canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), tile1ResID), 256, 256, true), 0, 0, null);
canvas.save();
}
catch (Exception e) {
}
canvas.save();
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
now I want to make it as background. So that the user can add an image or draw on it.
How can I set it as background?
Is it possible to add the image and draw by finger at the same time?
I use this code for draw:
#Override
public void onClick(View arg0) {
try {
Bitmap gestureImg = gesture.getGesture().toBitmap(100, 100, 8, Color.BLACK);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gestureImg.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("draw", bArray);
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(Activity1.this, "No draw on the string", 3000).show();
}
}
and OnDragListener for add and move images.
I know that I should use the folowing code for background:
LinearLayout ll = new LinearLayout(this);
ll.setBackgroundResource(R.drawable.nn);
this.setContentView(ll);
but by using this code, I can't see other images.
Thanks in advance.
You can just draw on the main bitmap the other bitmaps:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
bmp = <load from resource>
Canvas canvas = new Canvas(bmp);
Bitmap gestureImg = <get bitmap from gesture or loading>
canvas.drawBitmap(gestureImg);
then load the final bitmap:
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
Or you can store the main bitmap and all other gesture/loaded bitmaps in separate objects and when you want to update the imgMap1 you make your combined bitmap;
Also to use as background the new bitmap use:
ll.setBackgroundDrawable( new BitmapDrawable( bmp ) );
I have PictureDrawable that I wish to save as an image (JPEG/PNG) but I can't seem to find any information how to go about this.
I tried this but it does not seem to work
PictureDrawable myDrawable = GetPictureDrawable();
Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
myDrawable.draw(new Canvas(bitmap));
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/MyLocation/MyImage.jpg"));
What am I doing wrongly?
//Convert PictureDrawable to Bitmap
private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable){
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}