Android: Create a mirror image of a view - java

I wrote a code that reflects the view of an ImageView in the splash activity. In order to implement this, I took three steps.
Create an ImageView in the layout_splash.xml file and also in the SplashActivity.java.
Call the setImageBitmap method with the reflected ImageView variable
Declare a method that reflects the view of the image.
And here is the code.
public class SplashActivity extends Activity {
private ImageView ivLogo;
private SharedPreferences appPreferences;
private Typeface typeface;
private TextView tvAppName;
private boolean isAppInstalled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
String appName = getResources().getString(R.string.app_name);
appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
isAppInstalled = appPreferences.getBoolean("isAppInstalled", false);
if(isAppInstalled == false) {
Intent shortcutIntent = new Intent(getApplicationContext(), SplashActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher));
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(intent);
SharedPreferences.Editor editor = appPreferences.edit();
editor.putBoolean("isAppInstalled", true);
editor.commit();
}
// Set the app name's font
typeface = Typeface.createFromAsset(getAssets(), "fonts/Catull.ttf");
tvAppName = (TextView) findViewById(R.id.tvAppName);
tvAppName.setTypeface(typeface);
Bitmap originalImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_gruppo);
ivLogo = new ImageView(this);
ivLogo.setImageBitmap(getReflection(originalImage));
Handler hd = new Handler();
hd.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(), InitialActivity.class);
startActivity(intent);
// Implement the animation on activity change
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
finish();
}
}, 1200);
}
public Bitmap getReflection(Bitmap image) {
// The gap we want between the reflection and the original image
final int reflectionGap = 4;
// Get the bitmap from the mipmap folder
Bitmap originalImage = image;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
// This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
// Create a Bitmap with the flip matrix applied to it.
// We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
height / 2, width, height / 2, matrix, false);
// Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Bitmap.Config.ARGB_8888);
// Create a new Canvas with the bitmap that's big enough for
// the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
// Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw the reflection Image
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
// Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0,
originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
// Set the paint to use this shader (linear gradient)
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
}
But when running the application, I don't see the reflected image but just the plain one. Something wrong with the code?

Problems always occur from the very small things. In here the problem is that the ivLogo variable was not added into the content view. So the ivLogo must be added in the onCreate method like this,
ivLogo = (ImageView) findViewById(R.id.ivLogo);
instead of
ivLogo = new ImageView();

Related

Android App crashes with Simple draw to canvas, disp Bitmap

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
int height = this.getWindow().getDecorView().getHeight();
int width = this.getWindow().getDecorView().getWidth();
bitmap = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888 );
canvas = new Canvas(bitmap);
imageView = findViewById(R.id.imageView);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button){
canvas.drawColor(Color.RED);
}
imageView.setImageBitmap(bitmap);
}
}
Does anyone have any idea why the above code snippet for Android Studio would cause the app to crash constantly? I'm new to Android Studio and I want to get used to building rectangles and shapes before anything more, but it seems I'm having difficulty with even that.
Displays error of drawing Bitmap with values not > 0, but the issue is that after using a print function in onClick, grabbing height or width from either window or the imageView, I am returned a value > 0, so I don't understand.
You are getting height and width in onCreate method before view has been drawn and thus resulting in returning height 0, width 0 since android system don't know exact width and height of view.You can use some method like post(Runnable) to know if view has drawn.Modify you code like below.
View view = this.getWindow().getDecorView();
view.post( new Runnable() {
#Override
public void run() {
width = view.getMeasuredWidth();
height = view.getMeasuredHeight();
bitmap = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888 );
canvas = new Canvas(bitmap);
}
});

Place Drawable on Imageview using PorterDuff.Mode.SRC_ATOP

I have an ImageView:
ImageView imageView = findViewById(R.id.imageView);
I would like to achieve something like this (Atop figure)
drawable1 is the original ImageView image, drawable2 is the one I want to place over it:
Drawable drawable1 = AppCompatResources.getDrawable(context, drawable1);
Drawable drawable2 = AppCompatResources.getDrawable(context, drawable2);
LD layerDrawable = new LD(new Drawable[]{
drawable1,
drawable2,
});
imageView.setImageDrawable(layerDrawable);
LD class:
public class LD extends LayerDrawable
{
private Paint p = new Paint();
public LD(Drawable[] layers) {
super(layers);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
int count = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);
for (int i = 0, numberOfLayers = getNumberOfLayers(); i < numberOfLayers; ++i) {
this.getDrawable(i).draw(canvas);
canvas.saveLayer(null, p, Canvas.ALL_SAVE_FLAG);
}
canvas.restoreToCount(count);
}
}
However this doesn't work, because the image I place over (drawable2) is placed over the whole imageView, not just over the non-transparent contents of the drawable1 image.
How do I achieve Atop figure (placing drawable2 only over the 'filled content' of drawable1)?
Edit:
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
canvas.drawBitmap(bitmap1, 0, 0, null);
canvas.drawBitmap(bitmap2, 0, 0, p);

How to add Custom color Effect on My Custom camera in android

I want to create my custom camera with supports different color
effects for taking images ... I want to custom color effect on my
camera . i put some effect that is Built_In in device but i have no
idea that how i apply other effect like AFTER SNOW FALLING EFFECT
from here and so many other Color Effects.
Please Give me some hints or any link that is helpful for me
My code for effect is
((ImageView)findViewById(R.id.e1)).setOnClickListener(onButtonClick);
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.e1: MonoEffect();
break;}
}
};
private void MonoEffect()
{
Camera.Parameters parameters =mCamera.getParameters();
parameters.setColorEffect(android.hardware.Camera.Parameters.EFFECT_MONO);
mCamera.setParameters(parameters);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraPreviewLayout = (FrameLayout) findViewById(R.id.camera_preview);
//this code is holding an realtime overlay
RelativeLayout layout = (RelativeLayout) findViewById(R.id.preview);
FrameLayout fr = new FrameLayout(this);
fr.setBackgroundResource(R.drawable.snow);
ImageView b1 = new ImageView(this);
b1.setBackgroundResource(R.drawable.snow);
fr.addView(b1);
layout.addView(fr);
/*one solution could be,you if you want a real-time effect on your camera layout,you can add an overlay on the preview as given up.snow is a png format picture with transparent background */ after that... add both the camera output and ta transparent snoweffect as..
Bitmap cameraBitmap =BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap overlayBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.snow);
Bitmap cameraScaledBitmap = Bitmap.createScaledBitmap(cameraBitmap, 1200, 1600, true);
int wid = cameraScaledBitmap.getWidth();
int hgt = cameraScaledBitmap.getHeight();
Bitmap newImage = Bitmap.createBitmap(wid,hgt, Bitmap.Config.ARGB_8888);
Bitmap overlayScaledBitmap = Bitmap.createScaledBitmap(overlayBitmap, wid, hgt, true);
Canvas canvas = new Canvas(newImage);
canvas.drawBitmap(cameraBitmap , 0, 0, null);
canvas.drawBitmap(overlayScaledBitmap , 0, 0, null);
now you have got your final bitmap as named overlayScaledBitmap.now save it.dont tension about 1200,1600.i just scaled both the camera output bitmap and the snow transparent png as same size.i am currently working on the same project as you qustioned.i would like to take any suggetion from you. https://www.facebook.com/mohammad.mukul.37

How to draw on Camera Preview

for some time I've been working on this app, that allows user to take photos. The interesting thing about it, is that there should be some lines drawn over camera preview. The problem is that I'm not quite sure how to do this. I do have codes to initiate camera and to draw line, but I do not know how to merge them.
I use this code to initiate camera on button click:
initCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
/*Intent nextScreen = new Intent(getActivity().getApplicationContext(), CameraActivity.class);
startActivity(nextScreen);*/
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
And here's how I usually draw lines:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
imageView1 = (ImageView) findViewById(R.id.imageView1);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
bmp = Bitmap.createBitmap(width, height, conf);
canvas = new Canvas(bmp);
p = new Paint();
p.setColor(Color.RED);
imageView1.setImageBitmap(bmp);
p.setStrokeWidth(5);
canvas.drawLine(0, height/2, width, height/2, p);
You will need an overlay to draw on top of the live camera preview. The overlay is a child class of the surface the preview is drawn on. The preview class looks something like this:
class Preview extends ViewGroup implements SurfaceHolder.Callback, Camera.PreviewCallback
{
Preview(Context context)
{
super(context);
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
mSurfaceView = new SurfaceView(PreviewContext);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
PreviewCameraOverlay = new CameraOverlay(context);
addView(PreviewCameraOverlay);
}
// Additional functions like:
// surfaceChanged(SurfaceHolder holder, int format, int width, int height)
// onPreviewFrame(byte[] data, Camera pCamera)
// etc.
}
protected class CameraOverlay extends View
{
public CameraOverlay(Context context)
{
super(context);
setWillNotDraw(false);
setBackgroundColor(Color.TRANSPARENT);
setAlpha(1f);
OverlayPaint = new Paint[PaintColors];
}
// Additional functions:
// onDraw(Canvas canvas)
// onMeasure(int widthMeasureSpec, int heightMeasureSpec)
}
From your main activity you would call: Preview CameraPreview = new Preview(this); and draw whatever it is you want to draw from CameraOverlay's onDraw().

Darken/Dim/Blur Activity when navigation drawer is open

I am using LDrawer in my project. I need to make the activity which is hosting the navigation drawer darken/dim/blur when the navigation drawer is opened.
I have gone through similar questions on Stackoverflow and I have not found a satisfiying answer.
Is there any simple trick to make the activity's layout darken/dim/blur when I open my NavigationDrawer
I have the RelativeLayout of my activity defined as
RelativeLayout myActivity = (RelativeLayout) findViewById(R.id.myActivity)
I have the toggle code for NavigationDrawer below
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
//I want to manipulate myActivity's Layout here
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
Is there any simple trick to make the activity's layout Darken/Dim/Blur when I open my NavigationDrawer ?
Yes, you can simply change the background image of your activity as Blur when you open the drawer.
Other way is change the alpha or your activity simply by setalpha() and pass the value how much change you want.
If you have list control on your activity and you want to make that blur then below code will work.
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
Bitmap blurBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.invitation_blur_bg);
Rect rect = new Rect(0, 0, blurBitmap.getWidth(), blurBitmap.getHeight());
Implement the OnScrollListener on your activity or fragment where you want to apply this.
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
for (int i = 0; i < listview.getChildCount(); i++) {
View c = listview.getChildAt(i);
Rect r = new Rect();
c.getHitRect(r);
RelativeLayout llItemBg = ((RelativeLayout ) c.findViewById(R.id.root_layout of list item);
Drawable d = new BitmapDrawable(getResources(), cropImage(r,c));
itemBackground.setBackgroundDrawable(d);
}
}
private Bitmap cropImage(Rect r, View c2) {
Bitmap bmOverlay = Bitmap.createBitmap(screenWidth - 60,
c2.getHeight(), Bitmap.Config.ARGB_8888);
Rect rect1=new Rect(0, 0, bmOverlay.getWidth(), bmOverlay.getHeight());
Paint p = new Paint();
Canvas c = new Canvas(bmOverlay);
rect.right = r.right;
rect.top = rect.top;
rect.bottom = r.bottom / 2;
c.drawBitmap(blurBitmap, r, rect1, p);
return bmOverlay;
}

Categories