Have to Convert the code from native Android to Xamarin Android - android

I get a problem with converting code from native Android JAVA code to Xamarin C# Android code:
I have a class ThumbnailStrip:
How to set Orientation
LayOutParameters
OnClickListener
class ThumbnailStrip extends FrameLayout {
Context con;
Rotator rotator;
CustomImageView images;
int count;
Bitmap bitmap;
double viewHeight, viewWidth;
private boolean isDown;
private float X,Y,dX,dY,diffX,diffY;
private boolean NEXT,PREVIOUS;
LinearLayout thumbLayout;
public ThumbnailStrip(Context context, SfRotator _imageSlider, double height, double width) {
super(context);
con = context;
rotator = _imageSlider;
thumbLayout = new LinearLayout(context);
if (rotator.getNavigationStripPosition() == NavigationStripPosition.Top || rotator.getNavigationStripPosition() == NavigationStripPosition.Bottom)
thumbLayout.setOrientation(LinearLayout.HORIZONTAL);
else
thumbLayout.setOrientation(LinearLayout.VERTICAL);
if (thumbLayout.getOrientation() == LinearLayout.HORIZONTAL) {
viewHeight = height-10;
viewWidth = width / 5;
} else {
viewHeight = height / 5;
viewWidth = width-10;
}
createThumbnails(con);
}
Timer thumbTimer;boolean thumbStart,isDynamicView;
public ThumbnailStrip(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void createThumbnails(Context con) {
if (rotator.getDataSource() != null) {
count = rotator.getDataSource().size();
for (int i = 0; i < count; i++) {
View view;
if(rotator.getAdapter()!=null && rotator.getAdapter().getThumbnailView(rotator,i)!=null) {
view = rotator.getAdapter().getThumbnailView(rotator, i);
isDynamicView = true;
}
else {
if(rotator.getDataSource().get(i).getContent()!=null) {
view = rotator.getDataSource().get(i).getContent();
isDynamicView = false;
}
else
{
ImageView imageView = new ImageView(getContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
int resID = getResources().getIdentifier(rotator.getDataSource().get(i).getImageContent(), "drawable", getContext().getPackageName());
bitmap = BitmapFactory.decodeResource(getResources(), resID);
imageView.setImageBitmap(bitmap);
view=imageView;
isDynamicView = false;
}
}
view.setLayoutParams(new ViewGroup.LayoutParams(rotator.getWidth(),rotator.getHeight()));
images = new CustomImageView(con,view , (float) viewWidth, (float) viewHeight,isDynamicView);
images.setClickable(true);
images.setPadding(6, 0, 0, 0);
if(thumbLayout.getOrientation()==LinearLayout.VERTICAL) {
images.setPadding(6, 6, 0, 0);
}
images.setIndex(i);
if (i == rotator.getSelectedIndex()) {
images.setSelectedImage(true);
}
images.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
LayoutParams itemLayout;
itemLayout = new LayoutParams((int) viewWidth, (int) (viewHeight), Gravity.CENTER_VERTICAL);
itemLayout.setMargins(6, 6, 0, 0);
thumbLayout.addView(images, itemLayout);
//Especially I don't know how to set OnCliCkListener,Please help me with a solution.
images.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (rotator.isEnableAutoPlay()) {
rotator.isAnimationinteracted = true;
}
final CustomImageView imgView = (CustomImageView) v;
if (imgView.getIndex() > rotator.getSelectedIndex())
rotator.setPlayDirection(PlayDirection.MoveBackward);
else
rotator.setPlayDirection(PlayDirection.MoveForward);
if (imgView.getIndex() != rotator.getSelectedIndex()) {
rotator.setSelectedIndex((imgView).getIndex());
if (rotator.isEnableAutoPlay()) {
thumbStart = true;
}
}
}
});
}
this.addView(thumbLayout);
}
}
}
Pls, Help me to convert.

Layout Parameters in Xamarin is like this:
LinearLayout linear = new LinearLayout(this);
ImageView image = new ImageView(this);
LinearLayout.LayoutParams linearLayoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent,
LinearLayout.LayoutParams.FillParent);
linear.LayoutParameters = linearLayoutParams;
Cheking Orientation like this:
if(linear.Orientation == Orientation.Horizontal){
}
onCLick Listener in Java will convert into Events like this
image.Click += (sender, e) => {
};

images.Click += (sender, e) =>
{
if (rotator.isEnableAutoPlay())
{
rotator.isAnimationinteracted = true;
}
CustomImageView imgView = (CustomImageView)view;
if (imgView.getIndex() > rotator.getSelectedIndex())
rotator.playDirection = PlayDirection.MoveBackward;
else
rotator.playDirection = PlayDirection.MoveForward;
if (imgView.getIndex() != rotator.getSelectedIndex())
{
rotator.setSelectedIndex((imgView).getIndex());
if (rotator.isEnableAutoPlay())
{
thumbStart = true;
}
}
};

Related

Android Selectable TextViewer SetHighlightedText

I am Using SelectableTextview in my e-book app where i want to highlight any text from the book. The text is being highlighted by SelectableTextViewer class, and i am saving the selected text in database. Now i want when the user open the e-book next time the same text should be highlighted as it is. But there is no method of setting selected text. How can i solve this problem. Please help me
SelectableTextviewer.java
public class SelectableTextViewer extends RelativeLayout {
private ImageView imgStartSelect;
public static int mStartSelect = -1;
private ImageView imgEndSelect;
public static int mEndSelect = -1;
private int mImgWidth = 40;
private int mImgHeight = 50;
private TextView textView;
private View mCurrentControlFocused;
public static interface ISelectableTextViewerListener {
public void updateSelection(SelectableTextViewer selectableTextViewer);
public void endSelectingText(SelectableTextViewer selectableTextViewer,
String selectedText);
public void stopSelectingText(
SelectableTextViewer selectableTextViewer, String selectedText);
}
private ISelectableTextViewerListener selectableTextViewerListener;
public static BackgroundColorSpan spanBackgroundColored;
public void setSelectableTextViewerListener(
ISelectableTextViewerListener selectableTextViewerListener) {
this.selectableTextViewerListener = selectableTextViewerListener;
}
public SelectableTextViewer(Context context) {
super(context);
if (!isInEditMode()) {
this.initControls();
}
}
public SelectableTextViewer(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
this.initControls();
}
}
public SelectableTextViewer(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
if (!isInEditMode()) {
this.initControls();
}
}
private void initControls() {
this.spanBackgroundColored = new BackgroundColorSpan(Color.YELLOW);
this.textView = new TextView(getContext());
this.addView(textView);
this.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showSelectionControls();
int[] location = { 0, 0 };
getLocationOnScreen(location);
System.out.println("getLocationOnScreen:" + location[0] + "\t"
+ location[1]);
return false;
}
});
this.createImgControllersForSelection();
}
protected void disallowIntercept(Boolean disallowIntercept) {
this.getParent().requestDisallowInterceptTouchEvent(disallowIntercept);
}
protected void createImgControllersForSelection() {
this.imgStartSelect = new ImageView(getContext());
this.imgEndSelect = new ImageView(getContext());
this.imgStartSelect.setImageResource(R.drawable.cursor);
this.imgEndSelect.setImageResource(R.drawable.cursor);
this.addView(imgStartSelect, mImgWidth, mImgHeight);
this.addView(imgEndSelect, mImgWidth, mImgHeight);
OnClickListener onClickForChangeFocus = new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentControlFocused = v;
}
};
this.imgEndSelect.setOnClickListener(onClickForChangeFocus);
this.imgStartSelect.setOnClickListener(onClickForChangeFocus);
OnTouchListener onTouchSelectionControl = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
disallowIntercept(true);
mCurrentControlFocused = v;
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
int[] location = { 0, 0 };
getLocationOnScreen(location);
LayoutParams mParams = (LayoutParams) v
.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
// + insideScrollView.getScrollY();
mParams.leftMargin = x - mImgWidth / 2 - location[0];
if (x <= 0) {
mParams.leftMargin = mImgWidth;
} else if (x > (getMeasuredWidth() - mImgWidth)) {
mParams.leftMargin = getMeasuredWidth() - mImgWidth;
}
// TODO Must calculate all padding control
mParams.topMargin = (int) (y - (location[1] + mImgHeight * 1.5f));
if (mParams.topMargin <= 1) {
mParams.topMargin = 1;
}
v.setLayoutParams(mParams);
updateSelectionByMovementImgControls(mParams.leftMargin,
mParams.topMargin);
break;
case MotionEvent.ACTION_UP:
if (selectableTextViewerListener != null) {
selectableTextViewerListener.endSelectingText(
SelectableTextViewer.this, getSelectedText());
}
break;
default:
disallowIntercept(false);
break;
}
return true;
}
};
this.imgEndSelect.setOnTouchListener(onTouchSelectionControl);
this.imgStartSelect.setOnTouchListener(onTouchSelectionControl);
this.imgEndSelect.setVisibility(View.GONE);
this.imgStartSelect.setVisibility(View.GONE);
}
public void updateSelectionByMovementImgControls(int x, int y) {
if (mCurrentControlFocused.equals(imgStartSelect)) {
this.mStartSelect = getOffsetByCoordinates(x + mImgWidth / 2, y);
} else if (mCurrentControlFocused.equals(imgEndSelect)) {
this.mEndSelect = getOffsetByCoordinates(x + mImgWidth / 2, y);
}
updateSelectionSpan();
}
protected Layout updateSelectionSpan() {
Layout retLayout = this.textView.getLayout();
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
if (this.mStartSelect > this.mEndSelect) {
int temp = mEndSelect;
this.mEndSelect = mStartSelect;
this.mStartSelect = temp;
showSelectionControls();
}
SpannedString spannable = (SpannedString) this.textView.getText();
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
ssb.setSpan(this.spanBackgroundColored, this.mStartSelect,
this.mEndSelect, Spannable.SPAN_USER);
this.textView.setText(ssb);
this.textView.requestLayout();
if (this.selectableTextViewerListener != null) {
this.selectableTextViewerListener.updateSelection(this);
}
}
return retLayout;
}
protected void showSelectionControls() {
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
Layout layout = updateSelectionSpan();
Rect parentTextViewRect = new Rect();
LayoutParams startLP = (LayoutParams) this.imgStartSelect
.getLayoutParams();
float xStart = layout.getPrimaryHorizontal(this.mStartSelect)
- mImgWidth / 2;
float yStart = layout.getLineBounds(
layout.getLineForOffset(this.mStartSelect),
parentTextViewRect);
startLP.setMargins((int) xStart, (int) yStart, -1, -1);
this.imgStartSelect.setLayoutParams(startLP);
this.imgStartSelect.setVisibility(View.VISIBLE);
LayoutParams endLP = (LayoutParams) this.imgEndSelect
.getLayoutParams();
float xEnd = layout.getPrimaryHorizontal(this.mEndSelect)
- mImgWidth / 2;
float yEnd = layout.getLineBounds(
layout.getLineForOffset(this.mEndSelect),
parentTextViewRect);
endLP.setMargins((int) xEnd, (int) yEnd, -1, -1);
this.imgEndSelect.setLayoutParams(endLP);
this.imgEndSelect.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (this.imgStartSelect != null) {
if (this.imgStartSelect.getVisibility() == View.GONE) {
this.onTouchDownCalcSelections(event);
disallowIntercept(false);
} else {
this.stopSelecting();
}
}
} else {
this.disallowIntercept(false);
}
return super.onTouchEvent(event);
}
private void hideSelectionControls() {
this.imgStartSelect.setVisibility(View.GONE);
this.imgEndSelect.setVisibility(View.GONE);
}
private int getOffsetByCoordinates(int x, int y) {
int retOffset = -1;
Layout layout = this.textView.getLayout();
if (layout != null) {
int line = layout.getLineForVertical(y);
retOffset = layout.getOffsetForHorizontal(line, x);
}
return retOffset;
}
private void onTouchDownCalcSelections(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
this.mStartSelect = getOffsetByCoordinates(x, y);
if (this.mStartSelect > -1) {
// Calculate text end
String tempStr = this.textView.getText().toString();
tempStr = tempStr.substring(this.mStartSelect);
Pattern pt = Pattern.compile("\\s");
Matcher mt = pt.matcher(tempStr);
if (mt.find()) {
String match = mt.group(0);
tempStr = tempStr.substring(0, tempStr.indexOf(match));
}
this.mEndSelect = this.mStartSelect + tempStr.length();
}
}
public void setText(SpannableStringBuilder builder) {
this.textView.setText(builder);
}
public ImageView getImgEndSelect() {
return imgEndSelect;
}
public ImageView getImgStartSelect() {
return imgStartSelect;
}
/**
* For this all doing
*
* #return
*/
public String getSelectedText() {
String retSelectedString = null;
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
retSelectedString = this.textView.getText()
.subSequence(this.mStartSelect, this.mEndSelect).toString();
}
return retSelectedString;
}
/**
* Hides cursors and clears
*
* #return
*/
public void stopSelecting() {
this.hideSelectionControls();
SpannedString spannable = (SpannedString) this.textView.getText();
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
this.setText(ssb);
if (selectableTextViewerListener != null) {
selectableTextViewerListener.stopSelectingText(
SelectableTextViewer.this, getSelectedText());
}
}
}
you have to this method as re-use, customize this method as per your use. this is just a concept.
// text comes from textview.gettext or database text and invalidate the view.
protected Layout updateSelectionSpan(Strint text) {
Layout retLayout = this.textView.getLayout();
if (this.mStartSelect > -1 && this.mEndSelect > -1) {
if (this.mStartSelect > this.mEndSelect) {
int temp = mEndSelect;
this.mEndSelect = mStartSelect;
this.mStartSelect = temp;
showSelectionControls();
}
SpannedString spannable = (SpannedString) text;
SpannableStringBuilder ssb = new SpannableStringBuilder(spannable);
ssb.removeSpan(this.spanBackgroundColored);
ssb.setSpan(this.spanBackgroundColored, this.mStartSelect,
this.mEndSelect, Spannable.SPAN_USER);
this.textView.setText(ssb);
this.textView.requestLayout();
if (this.selectableTextViewerListener != null) {
this.selectableTextViewerListener.updateSelection(this);
}
}
return retLayout;
}

Wallpapers are scaling in time

Have some problem with wallpapers. This problem appear on some old and low-end devices. I'm trying to install wallpaper which may not scrolls(with device proportions) and they are normally installed. But after some time (2 or 3 days) wallpapers is scaling in 2 times(looks no pretty) and begin scrolling.
Here is part of code that install wallpapers:
public class WallpaperInstaller {
private Context mContext;
private CropImageView cropImageView;
private ImageLoader loader;
private boolean isCropped;
public WallpaperInstaller(Context context, final CropImageView civ, ImageLoader imageLoader) {
this.mContext = context;
this.cropImageView = civ;
this.loader = imageLoader;
this.isCropped = true;
}
public WallpaperInstaller(Context context, ImageLoader imageLoader) {
this.mContext = context;
this.loader = imageLoader;
this.isCropped = false;
}
public Thread setWallpaper(final String URL){
Thread setWallpaperThread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext);
try {
Bitmap croppedBitmap;
if(isCropped){
int scale = 1;
RectF rect = cropImageView.getActualCropRect();
int cropX = (int) rect.left * scale;
int cropY = (int) rect.top * scale;
int cropW = (int) rect.width() * scale;
int cropH = (int) rect.height() * scale;
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL), cropX, cropY, cropW, cropH);
} else {
try{
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL));
} catch (NullPointerException e){
loader.init(ImageLoaderConfiguration.createDefault(mContext));
croppedBitmap = Bitmap.createBitmap(loader.loadImageSync(URL));
}
}
boolean isScrollable = croppedBitmap.getWidth() > croppedBitmap.getHeight();
if(isScrollable){
wallpaperManager.setWallpaperOffsetSteps(-1, -1);
wallpaperManager.suggestDesiredDimensions(getWidth(croppedBitmap), getDisplay().getHeight());
wallpaperManager.setBitmap(Bitmap.createScaledBitmap(croppedBitmap, getWidth(croppedBitmap), getDisplay().getHeight(), false));
} else{
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(getDisplay().getWidth(), getDisplay().getHeight());
wallpaperManager.setBitmap(Bitmap.createScaledBitmap(croppedBitmap, getDisplay().getWidth(), getDisplay().getHeight(), false));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private int getWidth(Bitmap bitmap){
return (int)((float)getDisplay().getHeight()*(float)bitmap.getWidth()/(float)bitmap.getHeight());
}
private Display getDisplay(){
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
return windowManager.getDefaultDisplay();
}
});
return setWallpaperThread;
}
}
Thanks for your help.
Try adding next lines:
wallpaperManager.forgetLoadedWallpaper();
wallpaperManager.clear();

Android Segmented Control Design

How to change text color of Segmented Controls (if not selected), see below images:
I am getting like this (text in white color):
And want to design this (text in blue color):
Why i am getting space between 3 and 4 button ?
XML:
<com.om.go.widget.SegmentedButton
android:id="#+id/segmented"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
myapp:gradientColorOnStart="#ffffff"
myapp:gradientColorOnEnd="#ffffff"
myapp:gradientColorOffStart="#016de3"
myapp:gradientColorOffEnd="#016de3"
myapp:textStyle="#style/TextViewStyleHeaderButtonBlue"
myapp:strokeColor="#016de3"
myapp:strokeWidth="1dip"
myapp:cornerRadius="4dip"
myapp:btnPaddingTop="7dip"
myapp:btnPaddingBottom="7dip"
/>
SegmentedButton.java:-
public class SegmentedButton extends LinearLayout {
private StateListDrawable mBgLeftOn;
private StateListDrawable mBgRightOn;
private StateListDrawable mBgCenterOn;
private StateListDrawable mBgLeftOff;
private StateListDrawable mBgRightOff;
private StateListDrawable mBgCenterOff;
private int mSelectedButtonIndex = 0;
private List<String> mButtonTitles = new ArrayList<String>();
private int mColorOnStart;
private int mColorOnEnd;
private int mColorOffStart;
private int mColorOffEnd;
private int mColorSelectedStart;
private int mColorSelectedEnd;
private int mColorStroke;
private int mStrokeWidth;
private int mCornerRadius;
private int mTextStyle;
private int mBtnPaddingTop;
private int mBtnPaddingBottom;
private OnClickListenerSegmentedButton mOnClickListenerExternal;
public SegmentedButton(Context context) {
super(context);
}
public SegmentedButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedButton, 0, 0);
CharSequence btnText1 = a.getString(R.styleable.SegmentedButton_btnText1);
CharSequence btnText2 = a.getString(R.styleable.SegmentedButton_btnText2);
if (btnText1 != null) {
mButtonTitles.add(btnText1.toString());
}
if (btnText2 != null) {
mButtonTitles.add(btnText2.toString());
}
mColorOnStart = a.getColor(R.styleable.SegmentedButton_gradientColorOnStart, 0xFF0000);
mColorOnEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOnEnd, 0xFF0000);
mColorOffStart = a.getColor(R.styleable.SegmentedButton_gradientColorOffStart, 0xFF0000);
mColorOffEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOffEnd, 0xFF0000);
mColorStroke = a.getColor(R.styleable.SegmentedButton_strokeColor, 0xFF0000);
mColorSelectedEnd = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedEnd, 0xFF0000);
mColorSelectedStart = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedStart, 0xFF0000);
mStrokeWidth = a.getDimensionPixelSize(R.styleable.SegmentedButton_strokeWidth, 1);
mCornerRadius = a.getDimensionPixelSize(R.styleable.SegmentedButton_cornerRadius, 4);
mTextStyle = a.getResourceId(R.styleable.SegmentedButton_textStyle, -1);
mBtnPaddingTop = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingTop, 0);
mBtnPaddingBottom = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingBottom, 0);
a.recycle();
buildDrawables(mColorOnStart, mColorOnEnd, mColorOffStart, mColorOffEnd,
mColorSelectedStart, mColorSelectedEnd, mCornerRadius, mColorStroke,
mStrokeWidth);
if (mButtonTitles.size() > 0) {
_addButtons(new String[mButtonTitles.size()]);
}
}
public void clearButtons() {
removeAllViews();
}
public void addButtons(String ... titles) {
_addButtons(titles);
}
#SuppressWarnings("deprecation")
private void _addButtons(String[] titles) {
for (int i = 0; i < titles.length; i++) {
Button button = new Button(getContext());
button.setText(titles[i]);
button.setTag(new Integer(i));
button.setOnClickListener(mOnClickListener);
if (mTextStyle != -1) {
button.setTextAppearance(getContext(), mTextStyle);
}
if (titles.length == 1) {
// Don't use a segmented button with one button.
return;
} else if (titles.length == 2) {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else {
button.setBackgroundDrawable(mBgRightOn);
}
} else {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else if (i == titles.length-1) {
button.setBackgroundDrawable(mBgRightOn);
} else {
button.setBackgroundDrawable(mBgCenterOn);
}
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1);
addView(button, llp);
button.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
}
}
private void buildDrawables(int colorOnStart,
int colorOnEnd,
int colorOffStart,
int colorOffEnd,
int colorSelectedStart,
int colorSelectedEnd,
float crad,
int strokeColor,
int strokeWidth)
{
// top-left, top-right, bottom-right, bottom-left
float[] radiiLeft = new float[] {
crad, crad, 0, 0, 0, 0, crad, crad
};
float[] radiiRight = new float[] {
0, 0, crad, crad, crad, crad, 0, 0
};
float[] radiiCenter = new float[] {
0, 0, 0, 0, 0, 0, 0, 0
};
GradientDrawable leftOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
leftOn.setCornerRadii(radiiLeft);
GradientDrawable leftOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
leftOff.setCornerRadii(radiiLeft);
GradientDrawable leftSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
leftSelected.setCornerRadii(radiiLeft);
GradientDrawable rightOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
rightOn.setCornerRadii(radiiRight);
GradientDrawable rightOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
rightOff.setCornerRadii(radiiRight);
GradientDrawable rightSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
rightSelected.setCornerRadii(radiiRight);
GradientDrawable centerOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
centerOn.setCornerRadii(radiiCenter);
GradientDrawable centerOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
centerOff.setCornerRadii(radiiCenter);
GradientDrawable centerSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
centerSelected.setCornerRadii(radiiCenter);
List<int[]> onStates = buildOnStates();
List<int[]> offStates = buildOffStates();
mBgLeftOn = new StateListDrawable();
mBgRightOn = new StateListDrawable();
mBgCenterOn = new StateListDrawable();
mBgLeftOff = new StateListDrawable();
mBgRightOff = new StateListDrawable();
mBgCenterOff = new StateListDrawable();
for (int[] it : onStates) {
mBgLeftOn.addState(it, leftSelected);
mBgRightOn.addState(it, rightSelected);
mBgCenterOn.addState(it, centerSelected);
mBgLeftOff.addState(it, leftSelected);
mBgRightOff.addState(it, rightSelected);
mBgCenterOff.addState(it, centerSelected);
}
for (int[] it : offStates) {
mBgLeftOn.addState(it, leftOn);
mBgRightOn.addState(it, rightOn);
mBgCenterOn.addState(it, centerOn);
mBgLeftOff.addState(it, leftOff);
mBgRightOff.addState(it, rightOff);
mBgCenterOff.addState(it, centerOff);
}
}
private List<int[]> buildOnStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_selected, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_pressed});
return res;
}
private List<int[]> buildOffStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_selected, android.R.attr.state_enabled});
return res;
}
private GradientDrawable buildGradientDrawable(int colorStart, int colorEnd, int strokeWidth, int strokeColor) {
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[] { colorStart, colorEnd });
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke(strokeWidth, strokeColor);
return gd;
}
private OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Button btnNext = (Button)v;
int btnNextIndex = ((Integer)btnNext.getTag()).intValue();
if (btnNextIndex == mSelectedButtonIndex) {
return;
}
handleStateChange(mSelectedButtonIndex, btnNextIndex);
if (mOnClickListenerExternal != null) {
mOnClickListenerExternal.onClick(mSelectedButtonIndex);
}
}
};
#SuppressWarnings("deprecation")
private void handleStateChange(int btnLastIndex, int btnNextIndex) {
int count = getChildCount();
Button btnLast = (Button)getChildAt(btnLastIndex);
Button btnNext = (Button)getChildAt(btnNextIndex);
if (count < 3) {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else {
btnLast.setBackgroundDrawable(mBgRightOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else {
btnNext.setBackgroundDrawable(mBgRightOff);
}
} else {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else if (btnLastIndex == count-1) {
btnLast.setBackgroundDrawable(mBgRightOn);
} else {
btnLast.setBackgroundDrawable(mBgCenterOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else if (btnNextIndex == count-1) {
btnNext.setBackgroundDrawable(mBgRightOff);
} else {
btnNext.setBackgroundDrawable(mBgCenterOff);
}
}
btnLast.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
btnNext.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
mSelectedButtonIndex = btnNextIndex;
}
public int getSelectedButtonIndex() {
return mSelectedButtonIndex;
}
public void setPushedButtonIndex(int index) {
handleStateChange(mSelectedButtonIndex, index);
}
public void setOnClickListener(OnClickListenerSegmentedButton listener) {
mOnClickListenerExternal = listener;
}
public interface OnClickListenerSegmentedButton {
public void onClick(int index);
}
}

Scale the Bitmap to screen in Live wallpaper

I'm new in Android Programming I'm Trying to make slideshow animated live wallpaper and all ok but the problem is when I set the wallpaper the scale of image is stretched to screen I want it to scale to all the phone screens and when swipe the wallpaper get the right part of image I Want Advice about this problem.
my code is :
public class CustomWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
return new WallpaperEngine();
}
class WallpaperEngine extends Engine {
//Duration between slides in milliseconds
private final int SLIDE_DURATION = 8;
private int[] mImagesArray;
private int mImagesArrayIndex = 0;
private Thread mDrawWallpaper;
private String mImageScale = "Fit to screen";
private CustomWallpaperHelper customWallpaperHelper;
public WallpaperEngine() {
customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
mImagesArray = new int[] {R.drawable.image_1,R.drawable.image_2,R.drawable.image_3,R.drawable.image_4,R.drawable.image_5,R.drawable.image_6,R.drawable.image_7,R.drawable.image_8,R.drawable.image_9,R.drawable.image_10,R.drawable.image_11,R.drawable.image_12,R.drawable.image_13,R.drawable.image_14,R.drawable.image_15,R.drawable.image_16,R.drawable.image_17,R.drawable.image_18,R.drawable.image_19,R.drawable.image_20,R.drawable.image_21,R.drawable.image_22,R.drawable.image_23,R.drawable.image_24,R.drawable.image_25,R.drawable.image_26,R.drawable.image_27,R.drawable.image_28,R.drawable.image_29,R.drawable.image_30,R.drawable.image_31,R.drawable.image_32,R.drawable.image_33,R.drawable.image_34,R.drawable.image_35,R.drawable.image_36,R.drawable.image_37,R.drawable.image_38,R.drawable.image_39,R.drawable.image_40,R.drawable.image_41};
mDrawWallpaper = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
drawFrame();
incrementCounter();
Thread.sleep(SLIDE_DURATION);
}
} catch (Exception e) {
//
}
}
});
mDrawWallpaper.start();
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
//Draw background
customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
}
}
and the other class is:
public class CustomWallpaperHelper {
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to screen";
public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen";
private Context mContext;
private Resources mResources;
private Point screenSize = new Point();
private Bitmap bgImageScaled;
private Point bgImagePos = new Point(0, 0);
public CustomWallpaperHelper(Context mContext, Resources mResources) {
this.mContext = mContext;
this.mResources = mResources;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenSize.x = display.getWidth();
screenSize.y = display.getHeight();
;
}
private void scaleBackground() {
String imageScale = "Stretch to screen";
Bitmap bgImage = null;
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
bgImagePos = new Point(0, 0);
bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true);
}
}
public void setBackground(Canvas canvas) {
if (bgImageScaled != null) {
canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null);
} else {
canvas.drawColor(0xff000000);
}
}
public int getScreenWidth() {
return screenSize.x;
}
public int getScreenHeight() {
return screenSize.y;
}
public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) {
Point imagePos = new Point();
imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x)) / 2;
imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y)) / 2;
return imagePos;
}
public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) {
PointF canvasScale = new PointF(1f, 1f);
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = getScreenHeight() / (1f * imageHeight);
} else {
boolean tooWide = false;
boolean tooTall = false;
if (getScreenWidth() < imageWidth) {
tooWide = true;
}
if (getScreenHeight() < imageHeight) {
tooTall = true;
}
if (tooWide && tooTall) {
int x = imageWidth / getScreenWidth();
int y = imageHeight / getScreenHeight();
if (x > y) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
} else if (tooWide) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else if (tooTall) {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
}
return canvasScale;
}
}
I want Advice for this problem.
Thanks.
no need to do anything just Replace your below method with my code.
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
I would suggest that you crop the images instead of resizing them. Something like:
Rect r = new Rect(left, top, right, bottom);
Bitmap croppedImage = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1){
InputStream in = mContentResolver.openInputStream(mSaveUri);
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(in, false);
croppedImage = decoder.decodeRegion(r, null);
} else {
final int width = r.width();
final int height = r.height();
croppedImage = Bitmap.createBitmap(mBitmap, r.left, r.top, width, height);
croppedImage.setDensity(croppedImage.getDensity() * mOutputX / width);
}
return croppedImage;
Hope this helps...

How to select two image view on my activity and save the image states when we click on save button

My app Features:
Take photo from camera or picture gallery; //done
Collection of funny stickers; //done
Share created comical photos via email, mms etc. //done
Save 'stickered' photos in picture gallery; //done
Move, scale and rotate sticker images;
In this issue.. I am facing difficulty... I can able to add but I cant able to select the stickers after sticking two or more...while i am adding two or three stickers to an image then i can't able to select stickers individually. Or by selecting the stickers are changing automatically.
Facing this issue from last one week...
Can anyone suggest me any sample example program or supported lib file?
I tried Aviary but it is not suitable for this application.
Below is my List of Code:
public class MyMain extends Activity implements OnClickListener {
private static final int FROM_GALLERY = 200, CAMERA_PIC_REQUEST = 201,
SELECT_STICK_IMAGE = 10, FROM_SAVE_LIB = 11;
private ImageView mainImage, imgNew, imgSave, cat, stickyImage, done, flip,back,trash;
private RelativeLayout catWangMainImgLayout, rl_mainImageBottamBar1,
rl_mainImageBottamBar2;
public static int width, height, imWidth;
public OnTouchListener onTouchListenerStickImage = null;
private Bitmap camera_thumbnail;
static int l=0,m=0;
Pinch pig;
String image_id;
ArrayList stickyItemId = new ArrayList();
static Bitmap join;
private LinearLayout carHead, editImage;
private OnClickListener stickyImageListner, doneListener;
ArrayList sticky_list = new ArrayList();
public static int drag_x, drag_y;
int index = -1;
boolean stk_in_rect = false;
ImageView imageView_stky, imageView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.cat_wang_main);
Info.sticky_param = new ArrayList();
String type = getIntent().getExtras().getString("action_type");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Info.widthAfterZoom = Info.screenWidth = width = metrics.widthPixels;
imWidth = width - width / 15;
Info.screenHight = height = metrics.heightPixels;
stickyImage.setImageDrawable(getResources().getDrawable(Integer.parseInt(stickyItemId.get(index).toString())));
stickyImage.setBackgroundResource(R.drawable.image_border);
stickyImage.setPadding(20, 20, 20, 20);
Bitmap bmap3 = loadBitmapFromView(stickyImage);
imageView3.setOnTouchListener(null);
Pinch.matrix = Info.getMat(index);
imageView3.setOnTouchListener(Info.onTch);
imageView3.setImageBitmap(bmap3);
imageView3.bringToFront();
setMainBottanEditBar();
}
}
return true;
}
};
doneListener = new OnClickListener() {
#Override
public void onClick(View v) {
try {
l=0;
m=0;
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
imageView_stky.setImageBitmap(null);
imageView_stky.setAlpha(255);
stickyImage = new ImageView(CatWangMain.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setPadding(20, 20, 20, 20);
sticky_list.add(stickyImage);
Bitmap bmap2 = loadBitmapFromView(stickyImage);
imageView_stky.setOnTouchListener(null);
imageView_stky.setOnTouchListener(onTouchListenerStickImage);
imageView_stky.setImageBitmap(bmap2);
setSelectStickyMode();
Info.addMat(Pinch.matrix,index);
Pinch.editMood = false;
//int i =0;
Info.sticky_param.set(Info.current_matrix_id,new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
};
}
void camera() {
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// yes
Log.i("camera", "This device has camera!");
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} else {
// no
Log.i("camera", "This device has no camera!");
pickImage();
}
}
void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, FROM_GALLERY);
}
void createStickyImage(Bitmap bitmap, int id) {
pig = new Pinch(this, catWangMainImgLayout);
pig.addImage(bitmap, id);
}
super.onActivityResult(requestCode, resultCode, data);
int req = requestCode;
switch (req) {
case FROM_GALLERY:
setMainImageBg(resultCode, data);
break;
case SELECT_STICK_IMAGE:
addStickyImage(resultCode, data);
break;
case CAMERA_PIC_REQUEST:
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
// data.getExtras()
camera_thumbnail = (Bitmap) data.getExtras().get("data");
mainImage = (ImageView) findViewById(R.id.img_mainImg);
mainImage.setImageBitmap(camera_thumbnail);
} else {
finish();
}
} else {
}
break;
case FROM_SAVE_LIB:
Bundle b = getIntent().getExtras();
String sd = (String) b.getString("fromSaveImag");
if (resultCode == 13) {
callDialog_SaveToLib();
}
break;
default:
break;
}
}
void addStickyImage(int resultCode, Intent data){
if (resultCode == RESULT_OK) {
//sticky_param_added = false;
index = index +1;
Pinch.drag_x_value = Info.screenWidth/2;
Info.ceterOfX = Info.screenWidth/2;
Info.ceterOfY = Info.screenWidth/2;
Info.widthAfterZoom = Info.screenWidth;
Info.rotation = 0;
image_id = data.getStringExtra("img");
stickyItemId.add(image_id);
Toast.makeText(getApplicationContext(),"" + Integer.parseInt(image_id), Toast.LENGTH_SHORT).show();
stickyImage = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setImageDrawable(getResources().getDrawable(
Integer.parseInt(stickyItemId.get(stickyItemId.size() - 1).toString())));
stickyImage.setBackgroundResource(R.drawable.image_border);
stickyImage.setPadding(20, 20, 20, 20);
Bitmap bmap = loadBitmapFromView(stickyImage);
createStickyImage(bmap, 1);
setMainBottanEditBar();
}
}
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width,v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
void callDialogToGoHome() {
AlertDialog alert;
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(CatWangMain.this);
alertBuilder.setMessage("Are you sure you want to start over?");
alertBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
alert = alertBuilder.create();
alert.show();
}
void callDialog_SaveToLib() {
AlertDialog alertSaveLIb;
AlertDialog.Builder alertBuilderSaveLib = new AlertDialog.Builder(
CatWangMain.this);
alertBuilderSaveLib.setTitle("OMG !");
alertBuilderSaveLib.setMessage("yo! we totally saved that graphic !");
alertBuilderSaveLib.setPositiveButton("Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertSaveLIb = alertBuilderSaveLib.create();
alertSaveLIb.show();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.img_new:
callDialogToGoHome();
break;
case R.id.img_save:
try {
mainImage.buildDrawingCache();
Bitmap viewBitmap1 = mainImage.getDrawingCache();
if (catWangMainImgLayout.getChildCount() > 1) {
join = madeJoinBitmap(viewBitmap1);
} else {
join = viewBitmap1;
}
} catch (Exception e) {
e.printStackTrace();
}
Intent intentFlip = new Intent(CatWangMain.this, SaveImage.class);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
join.compress(CompressFormat.PNG, 80 , blob);
byte[] bitmapdata = blob.toByteArray();
intentFlip.putExtra("bitmap", bitmapdata);
startActivityForResult(intentFlip, FROM_SAVE_LIB);
break;
case R.id.img_cat:
Intent catWongItems = new Intent(this, CatWongStickyItems.class);
startActivityForResult(catWongItems, 10);
break;
default:
break;
}
}
private Bitmap madeJoinBitmap(Bitmap main) {
ImageView imageView = null;
Bitmap _bmp2 = null;
Bitmap bmOverlay = Bitmap.createBitmap(main.getWidth(), main.getHeight(), main.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(main, new Matrix(), null);
if (catWangMainImgLayout.getChildCount() > 1) {
for (int y = 0; y < sticky_list.size(); y++) {
imageView = (ImageView) sticky_list.get(y);
imageView.buildDrawingCache();
_bmp2 = imageView.getDrawingCache();
if((Matrix)Info.matrixList.get(y) != null)
{
canvas.drawBitmap(_bmp2, (Matrix)Info.matrixList.get(y),null);
}else {
canvas.drawBitmap(_bmp2, new Matrix(), null);
}
}
}
return bmOverlay;
}
void setMainBottanEditBar() {
editImage = (LinearLayout) findViewById(R.id.ll_edit);
editImage.setVisibility(View.VISIBLE);
rl_mainImageBottamBar1 = (RelativeLayout) findViewById(R.id.rl_bottam_bar);
rl_mainImageBottamBar1.setVisibility(View.INVISIBLE);
rl_mainImageBottamBar2 = (RelativeLayout) findViewById(R.id.rl_bottam_bar2);
rl_mainImageBottamBar2.setVisibility(View.VISIBLE);
carHead = (LinearLayout) findViewById(R.id.ll_catHead);
carHead.setVisibility(View.INVISIBLE);
done = (ImageView) findViewById(R.id.img_done);
done.setOnClickListener(doneListener);
back = (ImageView) findViewById(R.id.img_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
if(l==0)
{
imageView_stky.setAlpha(50);
l=1;
}
else
{
l=0;
imageView_stky.setAlpha(255);
}
setMainBottanEditBar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
flip = (ImageView) findViewById(R.id.img_flip);
flip.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "flip.. in progress",Toast.LENGTH_SHORT).show();
}
});
trash = (ImageView) findViewById(R.id.img_trash);
trash.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
imageView_stky = (ImageView) catWangMainImgLayout.getChildAt(Info.current_matrix_id+1);
imageView_stky.setImageBitmap(null);
imageView_stky.setAlpha(255);
stickyImage = new ImageView(CatWangMain.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
Info.screenWidth, Info.screenWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
stickyImage.setLayoutParams(params);
stickyImage.setImageDrawable(getResources().getDrawable(Integer.parseInt((String)stickyItemId.get(index))));
stickyImage.setPadding(20, 20, 20, 20);
sticky_list.add(stickyImage);
Bitmap bmap2 = loadBitmapFromView(stickyImage);
imageView_stky.setOnTouchListener(null);
imageView_stky.setOnTouchListener(onTouchListenerStickImage);
imageView_stky.setImageBitmap(bmap2);
setSelectStickyMode();
Info.addMat(Pinch.matrix, Info.current_matrix_id);
Pinch.editMood = false;
Info.sticky_param.set(Info.current_matrix_id,new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
catWangMainImgLayout.removeViewAt(catWangMainImgLayout.getChildCount() - 1);
catWangMainImgLayout.invalidate();
stickyItemId.remove(index);
setSelectStickyMode();
sticky_list.remove(index);
Info.sticky_param.remove(index);
Info.deleteMat(index);
Info.current_matrix_id = Info.current_matrix_id - 1;
index=index-1;;
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
void setSelectStickyMode() {
editImage = (LinearLayout) findViewById(R.id.ll_edit);
editImage.setVisibility(View.INVISIBLE);
rl_mainImageBottamBar1 = (RelativeLayout) findViewById(R.id.rl_bottam_bar);
rl_mainImageBottamBar1.setVisibility(View.VISIBLE);
rl_mainImageBottamBar2 = (RelativeLayout) findViewById(R.id.rl_bottam_bar2);
rl_mainImageBottamBar2.setVisibility(View.INVISIBLE);
carHead = (LinearLayout) findViewById(R.id.ll_catHead);
carHead.setVisibility(View.VISIBLE);
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_SIZE = 70;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
}
///////////////////////////////////////
public class Info {
static int screenWidth = CatWangMain.width, screenHight, stickyImageID = 90;
static OnTouchListener onTch;
public static ArrayList matrixList;
public static Point p1;
public static Point p2;
public static int ceterOfX, ceterOfY, widthAfterZoom = screenWidth, rotation;
public static ArrayList sticky_param;// = new ArrayList();;
public static int current_matrix_id = -1;
public static boolean checkPointInRect(float rx, float ry, int rw, int rh, int rot, float px, float py, boolean x){
double rotRad = (Math.PI * rot) / 180;
double dx = px - rx;
double dy = py - ry;
double h1 = Math.sqrt(dx * dx + dy * dy);
double currA = Math.atan2(dy,dx);
double newA = currA - rotRad;
double x2 = Math.cos(newA) * h1;
double y2 = Math.sin(newA) * h1;
if (x2 > - 0.5 * rw && x2 < 0.5 * rw && y2 > - 0.5 * rh && y2 < 0.5 * rh)
return true;
return false;
}
public static void addMat(Matrix m){
if(matrixList == null){
matrixList = new ArrayList();
}
}
public static void addMat(Matrix m, int position){
matrixList.set(position, m);
}
public static void deleteMat(int pos){
matrixList.remove(pos);
}
public static Matrix getMat(int pos){
return (Matrix)matrixList.get(pos);
}
public static int getMatrixSize(){
return matrixList.size();
}
}
////////////////////////////////////
public class Pinch //implements OnTouchListener
{
public static Matrix matrix = new Matrix();
public static Matrix savedMatrix = new Matrix();
RelativeLayout parent;
Activity context;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE, preRotate, rotate;
public int x,y;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private boolean singleTouch;
public static float scale = 1;
public static int drag_x_value = Info.screenWidth/2, drag_y_value = Info.screenWidth/2;
public static boolean editMood;
OnTouchListener touchLis = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
dumpEvent(event);
}else {
Info.ceterOfX = (int)mid.x;
Info.ceterOfY = (int)mid.y;
}
case MotionEvent.ACTION_POINTER_UP:
return true; // indicate event was handled
}
};
public Pinch(Activity context, RelativeLayout parent) {
this.context = context;
this.parent = parent;
}
public ImageView addImage(Bitmap image, int id) {
matrix = new Matrix();
ImageView tempImage = new ImageView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
tempImage.setId(Info.stickyImageID);
Info.stickyImageID = Info.stickyImageID + 1;
tempImage.setImageBitmap(image);
tempImage.setLayoutParams(params);
Info.onTch = touchLis;
tempImage.setOnTouchListener(Info.onTch);
matrix.postScale(01.00f, 01.00f);
tempImage.setScaleType(ScaleType.MATRIX);
tempImage.setImageMatrix(matrix);
Info.ceterOfY = Info.ceterOfX;
Info.addMat(Pinch.matrix);
Info.current_matrix_id = Info.getMatrixSize()-1;
Info.sticky_param.add(new SavedStickyImageParam(Info.ceterOfX, Info.ceterOfY, Info.widthAfterZoom, Info.rotation));
parent.addView(tempImage);
return tempImage;
}
set the tag by setTag() for each image view then, in On Click Event u can select the image by getTag()..

Categories

Resources