从3d图库中获取绘图,将其传递到其他活动,将图像视图保存到共享偏好中

时间:2017-06-04 11:19:17

标签: sharedpreferences adapter gallery avatar

我正在制作应用。我有一个带有imageAdapter,galleryView,gallery3dActivity和mainactivity的3d画廊。

ImageAdapter:

public class ImageAdapter extends BaseAdapter 
{
private ImageView[] mImages;

private Context mContext;
public List<Map<String, Object>> list;


public Integer[] imgs = { R.drawable.cat, R.drawable.dog, R.drawable.bird,
    R.drawable.chicken, R.drawable.cow, R.drawable.rabbit, R.drawable.pig, 
    R.drawable.sheep, R.drawable.donkey, R.drawable.deer, R.drawable.fox,
    R.drawable.helephant, R.drawable.tiger, R.drawable.leopard, R.drawable.lion, 
    R.drawable.monquey, R.drawable.owl, R.drawable.panda, R.drawable.pinguin, R.drawable.zebra,};
public String[] titles = { "The Cat.", "The Dog", "The Bird", "The Chicken", "The Cow", "The Rabbit", 
"The Pig", "The Sheep", "The Donkey", "The Deer","The Fox", "The Helephant", "The Tiger", "The Leopard", 
"The Lion", "The Monquey", "The Owl", "The Panda", "The Pinguin", "The Zebra"};

public ImageAdapter(Context c) 
{
    this.mContext = c;
    list = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < imgs.length; i++) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("image", imgs[i]);
        list.add(map);
    }
    mImages = new ImageView[list.size()];
}

public boolean createReflectedImages() 
{
    final int reflectionGap = 0;
    final int Height = 350;
    int index = 0;
    for (Map<String, Object> map : list) {
        Integer id = (Integer) map.get("image");

        Bitmap originalImage = BitmapFactory.decodeResource(mContext.getResources(), id);   
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        float scale = Height / (float)height;

        Matrix sMatrix = new Matrix();
        sMatrix.postScale(scale, scale);
        Bitmap miniBitmap = Bitmap.createBitmap(originalImage, 0, 0,
                originalImage.getWidth(), originalImage.getHeight(), sMatrix, true);

        originalImage.recycle();

        int mwidth = miniBitmap.getWidth();
        int mheight = miniBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(miniBitmap, 0, mheight/2, mwidth, mheight/2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(mwidth, (mheight + mheight / 2), Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(miniBitmap, 0, 0, null);
        Paint paint = new Paint();
        canvas.drawRect(0, mheight, mwidth, mheight + reflectionGap, paint);
        canvas.drawBitmap(reflectionImage, 0, mheight + reflectionGap, null);

        paint = new Paint();
        LinearGradient shader = new LinearGradient(0, miniBitmap.getHeight(), 0, bitmapWithReflection.getHeight()
                + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0, mheight, mwidth, bitmapWithReflection.getHeight() + reflectionGap, paint);

        ImageView imageView = new ImageView(mContext);
        imageView.setImageBitmap(bitmapWithReflection);
        imageView.setLayoutParams(new GalleryView.LayoutParams((int)(width * scale),
                (int)(mheight * 3 / 2.0 + reflectionGap)));
        imageView.setScaleType(ScaleType.MATRIX);
        mImages[index++] = imageView;
    }
    return true;
}

@Override
public int getCount() {
    return imgs.length;
}

@Override
public Object getItem(int position) {
    return mImages[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return mImages[position];
}

public float getScale(boolean focused, int offset) {
    return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}

}

图库视图:

public class GalleryView extends Gallery 
{
private Camera mCamera = new Camera();
private int mMaxRotationAngle = 45; 
private int mMaxZoom = -120;
private int mCoveflowCenter;

public GalleryView(Context context) 
{
    super(context);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs) 
{
    super(context, attrs);
    this.setStaticTransformationsEnabled(true);
}

public GalleryView(Context context, AttributeSet attrs, int defStyle) 
{
    super(context, attrs, defStyle);
    this.setStaticTransformationsEnabled(true);
}

public int getMaxRotationAngle() 
{
    return mMaxRotationAngle;
}

public void setMaxRotationAngle(int maxRotationAngle) 
{
    mMaxRotationAngle = maxRotationAngle;
}

public int getMaxZoom() 
{
    return mMaxZoom;
}

public void setMaxZoom(int maxZoom) 
{
    mMaxZoom = maxZoom;
}

private int getCenterOfCoverflow() 
{
    return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}

private static int getCenterOfView(View view) {
    return view.getLeft() + view.getWidth() / 2;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) 
{
    mCoveflowCenter = getCenterOfCoverflow();
    super.onSizeChanged(w, h, oldw, oldh);
} 

@Override
protected boolean getChildStaticTransformation(View child, Transformation trans) 
{
    final int childCenter = getCenterOfView(child);
    final int childWidth = child.getWidth();
    int rotationAngle = 0;

    trans.clear();
    trans.setTransformationType(Transformation.TYPE_BOTH);

    if (childCenter == mCoveflowCenter) 
    {
        transformImageBitmap((ImageView) child, trans, 0);  
    } 
    else 
    {
        rotationAngle = (int) ( ( (float) (mCoveflowCenter - childCenter) / childWidth ) * mMaxRotationAngle );
        if (Math.abs(rotationAngle) > mMaxRotationAngle) 
        {
            rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
        }
        transformImageBitmap((ImageView) child, trans, rotationAngle);
    }

    return true;
}

private void transformImageBitmap(ImageView child, Transformation trans, int rotationAngle) 
{
    mCamera.save();

    final Matrix imageMatrix = trans.getMatrix();
    final int imageHeight = child.getLayoutParams().height;
    final int imageWidth = child.getLayoutParams().width;
    final int rotation = Math.abs(rotationAngle);

    mCamera.translate(0.0f, 0.0f, -20.0f);

    // As the angle of the view gets less, zoom in
    if (rotation < mMaxRotationAngle)
    {
        float zoomAmount = (float) (mMaxZoom + (rotation * 1.0));
        mCamera.translate(0.0f, 0.0f, zoomAmount);
    }

    mCamera.rotateY(rotationAngle);
    mCamera.getMatrix(imageMatrix);
    imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
    imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

    mCamera.restore();
}
}

Gallery3DActivity:

public class Gallery3DActivity extends Activity {

private TextView tvTitle;   
private GalleryView gallery;    
private ImageAdapter adapter;
private ImageView Avatar;

@Override
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grallery_layout);

    initRes();
}

private void initRes(){
    tvTitle = (TextView) findViewById(R.id.tvTitle);
    gallery = (GalleryView) findViewById(R.id.mygallery);
    Avatar = (ImageView) findViewById(R.id.imageAvatar);
    adapter = new ImageAdapter(this);   
    adapter.createReflectedImages();
    gallery.setAdapter(adapter);

    gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            tvTitle.setText(adapter.titles[position]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    gallery.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(Gallery3DActivity.this, MainActivity.class);
            int grallery_layout = 0;
            Avatar.setImageResource(R.layout.grallery_layout);
            startActivity(i);
            Toast.makeText(Gallery3DActivity.this, "img " + (position+1) + " selected", Toast.LENGTH_SHORT).show();
        }
    });
}
}

gallery.setOnItemClickListener我尝试获取drawable并使用 id imageAvatar 在imageview中的主要活动上显示它,但它确实无效。没有运气,我尝试了很多方法。在我想使用共享首选项保存imageview new drawable之后,网格类型不起作用。

1 个答案:

答案 0 :(得分:0)

这是我工作的解决方案...... 我对gallery3dActivity的意图是:

@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) {
int selectedId = imgs[position]; 
Intent intent = new Intent(Gallery3DActivity.this,MainActivity.class);
intent.putExtra("imageId", selectedId);
startActivity(intent);
}

这会将意图内的选定drawable发送到我的主要活动, 在主要活动中,我收到意图并将其设置在imageview上:

Intent avatar = getIntent(); 
int imageId = avatar.getIntExtra("imageId", -0); 
// -0 would be a default value
// -1 will crash with a missing resource

if (getIntent().getExtras() != null)
{Avatar.setImageResource(imageId);
savedAvatar.setImageResource(imageId);
update.setVisibility(View.GONE);
}
else
{Avatar.setImageResource(R.mipmap.ic_launcher);
}

我的主要活动上有一个id更新的按钮,onclick调用setProfilePhoto:

public void setProfilePhoto(View view){
//code image to string
savedAvatar.buildDrawingCache();
Bitmap bitmap = savedAvatar.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image=stream.toByteArray();
String img_str = Base64.encodeToString(image, 0);

//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );

//save in sharedpreferences
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userphoto",img_str);
editor.commit();
update.setVisibility(View.GONE);
}

这将获得imageview drawingcache将其转换为bitmao将它们转换为字符串,将字符串返回到image以便能够在imageview上显示它并将字符串保存在sharedpreferences中。 我在oncreate方法上检索图像后调用2个方法:

checkFirstLogin();
prepareForm();
是这样的:

private void prepareForm() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
// If value for key not exist then return second param value - In this case "..."
String img_str=preferences.getString("userphoto", "");
if (!img_str.equals("")){
//decode string to image
String base=img_str;
byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
        Avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
        savedAvatar.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
    }
}

private void checkFirstLogin() {
    SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
    // If value for key not exist then return second param value - In this case true
    if (preferences.getBoolean("firstLogin", true)) {
        initProfile();
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstLogin", false);
        editor.commit();
    }
}

最后在方法chechfirstlogin里面调用initProfile方法:

private void initProfile() {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.commit();
}

将调用sharedpreferences。

这就是它,它完美地运行了代码,我希望这可以帮助某人,抱歉提出这么难的问题并做出如此大的答案。祝你有个美好的一天。